Will the main thread exiting kill the Async task?

java, multithreading

Solution

As mentioned here:

the method `supplyAsync`use `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);

Problem

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.

Original source