Reputation: 982
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?
Upvotes: 4
Views: 2253
Reputation: 13535
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);
Upvotes: 1
Reputation: 40098
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
Upvotes: 6