Search code examples
javamultithreadingasynchronouscompletable-futureforkjoinpool

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


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?


Solution

  • 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