使用CompletableFuture.runAsync()与ForkJoinPool.execute()

问题描述 投票:2回答:2

[没有将Executor传递到CompletableFuture.runAsync(),则使用公共ForkJoinPool。相反,对于要异步执行的简单任务(例如,我不需要链接其他任务),我可以只使用ForkJoinPool.commonPool().execute()

为什么一个应优先于另一个?例如,runAsync()是否相对于execute()有任何实质性开销?前者相对于后者有什么特殊优势吗?

java multithreading asynchronous completable-future forkjoinpool
2个回答
5
投票

[CompletableFuture不仅用于将来的异步对象,它还具有一些其他优点和功能,可使用FutureisDoneisCancelled等来跟踪isCompletedExceptionally任务。

为了简化监视,调试和跟踪,所有生成的异步任务都是标记接口CompletableFuture.AsynchronousCompletionTask的实例。

这里是一种情况,我可以解释使用ForkJoinPool.executeCompletableFuture.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

0
投票

ForkJoinPool.commonPool()。execute()返回void。您无法跟踪或控制任务的执行。

ForkJoinPool.commonPool()。submit()返回实现了Future的ForkJoinTask。您可以使用Future.isDone,Future.get()或Future.cancel等同步界面跟踪或取消任务。

CompletableFuture.runAsync返回CompletableFuture。除了同步接口之外,它还具有异步接口,该接口允许触发其他CompletableFutures,例如

 CompletableFuture.runAsync(task).thenAccept(anothertask);
© www.soinside.com 2019 - 2024. All rights reserved.