Will the main thread shutdown the Async task?

I am running a java8 application, it looks like after the main thread exits, the process will end.

I am using completableFuture to run an async task as shown below.

CompletableFuture cf = CompletableFuture.supplyAsync(() -> task.call());

        cf.thenRunAsync(() -> {
            try {
                System.out.println(Thread.currentThread());
                System.out.println((Double)cf.get() * 4.0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

      

I expect async to run as a separate thread, so exiting the main thread shouldn't cause the process to exit, but it doesn't.

I'm assuming the async job is running like a deamon thread? But I can't confirm.

+3


source to share


1 answer


As mentioned here :

method to supplyAsync

use ForkJoinPool.commonPool()

threadpool which is shared among all CompletableFutures

.

And as mentioned here

ForkJoinPool

uses threads in daemon mode, there is usually no need to explicitly disable such a pool after a program exits.



So that's it.

To avoid this, you need to pass an explicit executor, for example:

ExecutorService pool = Executors.newFixedThreadPool(5);
final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                ... }, pool);

      

+5


source







All Articles