I am using an ExecutoreService in Java 1.6, started simply by
ExecutorService pool = Executors.newFixedThreadPool(THREADS).
When my main thread is finished (along with all the tasks processed by the thread pool), this pool will prevent my program from shutting down until I explicitly call
pool.shutdown();
Can I avoid having to call this by somehow turning the internal thread managing used by this pool into a deamon thread? Or am I missing something here.
Probably simplest and preferred solution is in Marco13’s answer so don’t get fooled by vote difference (this answer is few years older) or acceptance mark (it just means that this solution was appropriate for OP circumstances, not that it is best in general).
You can use
ThreadFactoryto set threads inside Executor to daemons. This will affect executor service in a way that it will also become daemon thread so it (and threads handled by it) will stop if there will be no other non-daemon thread. Here is simple example:But if you want to get executor which will let its task finish, and at the same time will automatically call its
shutdown()method when application is complete, you may want to wrap your executor with Guava’sMoreExecutors.getExitingExecutorService.