Reputation: 21172
If I set up an ExecutorService
with a ThreadFactory
that spawns daemon threads, do I still need to explicitly call the shutdown()
method?
Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).build());
Upvotes: 5
Views: 2037
Reputation: 44240
Well, as per setDaemon
,
The Java Virtual Machine exits when the only threads running are all daemon threads.
So because you're using daemon threads your executor won't prevent your application from finishing. But that's not to say there's no reason to call shutdown
. You may still want to prevent any additional tasks from being submitted at some point before your application ends.
Test it if you like: (I removed the Guava stuff, but the principal is the same)
public static void main(String... args)
{
final ExecutorService executorService = Executors.newSingleThreadExecutor(r -> {
final Thread thread = new Thread(r);
thread.setDaemon(false); //change me
return thread;
});
executorService.submit(() -> { while (true){ System.out.println("busy"); } });
}
Upvotes: 2