简体   繁体   中英

Using CompletableFuture.runAsync() vs ForkJoinPool.execute()

Without passing an Executor to CompletableFuture.runAsync() , the common ForkJoinPool is used. Instead, for a simple task (eg, I do not need to chain different tasks) that I want to be executed asynchronously, I might just use ForkJoinPool.commonPool().execute() .

Why should one be preferred over the other? Eg, does runAsync() have any substantial overhead with respect to execute() ? Does the former have any specific advantages over the latter?

CompletableFuture Is not only used for asynchronous future objects, it has some additional advantages and features for tracking the Future task using isDone , isCancelled and isCompletedExceptionally etc..

To simplify monitoring, debugging, and tracking, all generated asynchronous tasks are instances of the marker interface CompletableFuture.AsynchronousCompletionTask.

Here is one scenario were i can explain difference between using ForkJoinPool.execute and CompletableFuture.runAsync

ForkJoinPool.execute While using execute method if any exception is thrown by Runnable task then execution will terminate abnormally, so you need try catch to handle any unexpected exceptions

 ForkJoinPool.commonPool().execute(()->{
     throw new RuntimeException();
 });

output :

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

CompletableFuture.runAsync But while using CompletableFuture you can have exceptionally to handle any unexpected exceptions

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

    }).exceptionally(ex -> {
        System.out.println("Exception handled");
        return null;
    });

Output :

Exception handled

ForkJoinPool.commonPool().execute() returns void. You can't track or control the execition of the task.

ForkJoinPool.commonPool().submit() returns ForkJoinTask which implements Future. You can track or cancel the task using synchronous interface like Future.isDone, Future.get(), or Future.cancel.

CompletableFuture.runAsync returns CompletableFuture. In addition to the synchronous interface, it has asynchronous interface which allows to trigger other CompletableFutures, eg

 CompletableFuture.runAsync(task).thenAccept(anothertask);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM