Search code examples
javajava-8completable-future

why runAsync method in CompletableFuture is not executing until unless we are calling get method on CompletableFuture?


So ideally when we are using threading concept, it will run the task asynchronously, So in the below snippet:

  CompletableFuture result=  CompletableFuture.runAsync(()->{
        System.out.println("1st Task Completed");

    });

While running this code in main method it is not printing "1st Task Completed" . if I will put result.get() then it's printing "1st Task Completed". So is the task is is executing whenever we are calling get method ?


Solution

  • If that's the only code in your main, the main method will most likely return (and end your program) before the async task has had a chance to run.

    Just add a Thread.sleep(1000); or something like that after your code and you should see the expected output.

    But we don't really know how long we need to wait, so a more robust approach would be to use a synchronization mechanism, for example:

    CountDownLatch done = new CountDownLatch(1);
    CompletableFuture.runAsync(()->{
      System.out.println("1st Task Completed");
      done.countDown();
    });
    done.await();