Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the main thread exiting kill the Async task?

I am running java8 application, it looks like once the main thread exit, the process will exit.

I am using completableFuture to start a async task like the following

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 will run as a separate thread, so main thread exit should not cause the process exit, but it turns out not true.

I guess the async job is running as the deamon thread? But cannot confirm.

like image 934
Adam Lee Avatar asked Jul 02 '26 10:07

Adam Lee


1 Answers

As mentioned here:

the method supplyAsyncuse ForkJoinPool.commonPool() threadpool which is shared among all CompletableFutures.

And as mentioned here

ForkJoinPool uses threads in daemon mode, there is typically no need to explicitly shutdown such a pool upon program exit.

So it seems that is the case.

To avoid this you need to pass an explicit executor like:

ExecutorService pool = Executors.newFixedThreadPool(5);
final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                ... }, pool);
like image 167
akhil_mittal Avatar answered Jul 05 '26 01:07

akhil_mittal