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

Chr*_* S. 4 java multithreading asynchronous forkjoinpool completable-future

不传递Executorto CompletableFuture.runAsync()ForkJoinPool则使用公共。相反,对于我想要异步执行的简单任务(例如,我不需要链接不同的任务),我可能只使用ForkJoinPool.commonPool().execute().

为什么应该优先考虑另一个?例如,是否runAsync()有任何实质性的开销execute()?前者比后者有什么特别的优势吗?

Dea*_*ool 5

CompletableFuture不仅用于异步未来对象,它还具有一些额外的优势和功能,用于Future使用isDoneisCancelledisCompletedExceptionally等跟踪任务。

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

这是一种场景,我可以解释使用ForkJoinPool.executeCompletableFuture.runAsync

ForkJoinPool.execute使用execute方法时,如果Runnable任务抛出任何异常,则执行将异常终止,因此您需要 try catch 来处理任何意外异常

 ForkJoinPool.commonPool().execute(()->{
     throw new RuntimeException();
 });
Run Code Online (Sandbox Code Playgroud)

输出 :

Exception in thread "ForkJoinPool.commonPool-worker-5" java.lang.RuntimeException
at JavaDemoTest/com.test.TestOne.lambda$2(TestOne.java:17)
Run Code Online (Sandbox Code Playgroud)

CompletableFuture.runAsync但是在使用时CompletableFuture你可能不得不exceptionally处理任何意外的异常

CompletableFuture<Void> complete = CompletableFuture.runAsync(() -> {
        throw new RuntimeException();

    }).exceptionally(ex -> {
        System.out.println("Exception handled");
        return null;
    });
Run Code Online (Sandbox Code Playgroud)

输出 :

Exception handled
Run Code Online (Sandbox Code Playgroud)