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
ExecutorService.submit( Callable )
would be preferred. Why mess with more than that?