对不起,标题令人困惑,我要尝试的是跟踪异步执行的方法引发异常的次数,同时还将成功执行的结果检索到类变量中。我认为我的实现尚不完善,在这里,CompletableFutures列表比List的CompletableFuture更合适吗?
public class testClass {
private List<Integer> resultNumbers;
public void testMethod() {
int exceptions = 0;
try {
methodWithFuture();
catch (InterruptedException | ExecutionException e) {
exceptions++;
}
System.out.println("Number of times the addNumber method threw an exception=" + exceptions);
}
public void methodWithFuture() throws InterruptedException, ExecutionException {
List<Integer> numbersList = Arrays.asList(new Integer[] { 1, 2, 3 })
CompletableFuture<List<Integer>> futuresList = CompletableFuture.supplyAsync(() ->
numbersList.parallelStream().map(number -> addNumber(number))).collect(Collectors.toList()),
new ForkJoinPool(3));
resultNumbers.addAll(futuresList.get());
}
}
因此,查看您的代码最多只能获得1个异常。对于对addNumber的每次调用,一个更好的CompletableFuture调用。然后检查是否异常。
public void testMethod(){
int exceptions = 0;
List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
List<CompletableFuture<Integer>> cfList = new ArrayList<>();
for(int number : numbersList){
CompletableFuture<Integer> cf = methodWithFuture(number);
cfList.add(cf);
}
CompletableFuture<Void> allOfCF = CompletableFuture.allOf(cfList.toArray(new CompletableFuture[0]));
try {allOf.get();} catch (InterruptedException | ExecutionException ignored) {}
int sum = 0;
for(CompletableFuture<Integer> cf : cfList){
if(cf.isCompletedExceptionally()){
exceptions ++;
} else {
sum += cf.get();
}
}
System.out.println("Number of times the addNumber method threw an exception=" + exceptions);
System.out.println("SUM " + sum);
}
public CompletableFuture<Integer> methodWithFuture(int number) {
return CompletableFuture.supplyAsync(() -> addNumber(number));
}
在这里,我已将每个调用addNumber
异步提交,并在使用完成后等待将它们全部加入allOf
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句