4

Without passing an Executor to CompletableFuture.runAsync(), the common ForkJoinPool is used. Instead, for a simple task (e.g., 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? E.g., does runAsync() have any substantial overhead with respect to execute()? Does the former have any specific advantages over the latter?

1
  • If all you want is a simple asynchronous task, I'd think that ExecutorService.submit( Callable ) would be preferred. Why mess with more than that? Commented Dec 15, 2019 at 16:27

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

1

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, e.g.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.