The various ExecutorService instances created by Executors and ForkJoinPool.commonPool() of course have quite different behaviour.
If you try the example program below (and its variants) you should see that it only prints "false". Since the services using daemon threads die when the main thread dies, this is of course to be expected. But I can't find this behaviour documented anywhere except in the source, so how can I be sure this won't change in the future?
And if I can't be sure if daemon threads will be used when I create ExecutorService instances like this, how should I create them in a way that guarantees the behaviour I want?
import java.util.concurrent.*;
class ExecutorsTest {
public static void main(String[] args) {
// These use normal threads
// ExecutorService es = Executors.newSingleThreadExecutor();
// ExecutorService es = Executors.newCachedThreadPool();
// These use daemon threads
ExecutorService es = Executors.newWorkStealingPool();
// ExecutorService es = ForkJoinPool.commonPool();
es.execute(() -> {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().isDaemon());
});
}
}