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());
});
}
}
You should not rely on undocumented features of specific JRE / JDK implementation.
If you want to make sure threads are daemons or have specific thread name, you can use ThreadFactory API to construct them:
Executors.newFixedThreadPool(int nThreads, ThreadFactory threadFactory)
For some reason there is no corresponded method in Executors API for WorkStealingPool
which accepts ThreadFactory
.