[没有将Executor
传递到CompletableFuture.runAsync()
,则使用公共ForkJoinPool
。相反,对于要异步执行的简单任务(例如,我不需要链接其他任务),我可以只使用ForkJoinPool.commonPool().execute()
。
为什么一个应优先于另一个?例如,runAsync()
是否相对于execute()
有任何实质性开销?前者相对于后者有什么特殊优势吗?
[CompletableFuture不仅用于异步将来的对象,它还具有一些其他优点和功能,可使用Future
,isDone和isCancelled等来跟踪isCompletedExceptionally任务。
为了简化监视,调试和跟踪,所有生成的异步任务都是标记接口CompletableFuture.AsynchronousCompletionTask的实例。
这里是一种情况,我可以解释使用ForkJoinPool.execute
和CompletableFuture.runAsync
之间的区别
ForkJoinPool.execute使用execute
方法时,如果Runnable
任务抛出任何异常,则执行将异常终止,因此您需要尝试catch来处理任何意外的异常
ForkJoinPool.commonPool().execute(()->{
throw new RuntimeException();
});
输出:
Exception in thread "ForkJoinPool.commonPool-worker-5" java.lang.RuntimeException
at JavaDemoTest/com.test.TestOne.lambda$2(TestOne.java:17)
CompletableFuture.runAsync但是在使用CompletableFuture
时,您可以让exceptionally
处理任何意外的异常
CompletableFuture<Void> complete = CompletableFuture.runAsync(() -> {
throw new RuntimeException();
}).exceptionally(ex -> {
System.out.println("Exception handled");
return null;
});
输出:
Exception handled