将CompletableFuture.runAsync()用于简单的异步任务

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

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

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

java multithreading asynchronous completable-future forkjoinpool
1个回答
3
投票

[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
© www.soinside.com 2019 - 2024. All rights reserved.