5

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()); 

1 Answer 1

2

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"); } }); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Actually I'm using a ScheduledExecutorService to clean up a cache. At this point I won't bother shutting it down. Thanks Michael

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.