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.
As mentioned here:
the method
supplyAsyncuseForkJoinPool.commonPool()threadpool which is shared among allCompletableFutures.
And as mentioned here
ForkJoinPooluses 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With