在不将Executor
传递到CompletableFuture.runAsync()
的情况下,使用公用ForkJoinPool
。相反,对于要异步执行的简单任务(例如,我不需要链接其他任务),我可能只使用ForkJoinPool.commonPool().execute()
。
为什么一个应优先于另一个?例如,runAsync()
相对于execute()
是否有任何实质性开销?前者比后者有什么特殊优势吗?
CompletableFuture不仅用于异步将来的对象,它还具有一些其他优点和功能,可使用isDone,isCancelled和{{3}来跟踪Future
任务}等。
为简化监视,调试和跟踪,所有生成的异步任务都是标记接口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
,
ForkJoinPool.commonPool()。execute()返回void。您无法跟踪或控制任务的执行。
ForkJoinPool.commonPool()。submit()返回实现Future的ForkJoinTask。您可以使用Future.isDone,Future.get()或Future.cancel等同步界面跟踪或取消任务。
CompletableFuture.runAsync返回CompletableFuture。除了同步接口之外,它还具有异步接口,该接口允许触发其他CompletableFuture,例如
CompletableFuture.runAsync(task).thenAccept(anothertask);