I am using an ExecutoreService in Java 1.6, started simply by
ExecutorService pool = Executors.newFixedThreadPool(THREADS).
When my main
You can use Guava's ThreadFactoryBuilder. I didn't want to add the dependency and I wanted the functionality from Executors.DefaultThreadFactory, so I used composition:
class DaemonThreadFactory implements ThreadFactory {
final ThreadFactory delegate;
DaemonThreadFactory() {
this(Executors.defaultThreadFactory());
}
DaemonThreadFactory(ThreadFactory delegate) {
this.delegate = delegate;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = delegate.newThread(r);
thread.setDaemon(true);
return thread;
}
}
If you only want to use it in one place, then you can inline the java.util.concurrent.ThreadFactory
implementation, e.g. for a pool with 4 threads you would write (example shown as a lambda assuming Java 1.8 or newer):
ExecutorService pool = Executors.newFixedThreadPool(4,
(Runnable r) -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
);
But I usually want all of my Thread factories to produce daemon threads, so I add a utility class as follows:
import java.util.concurrent.ThreadFactory;
public class DaemonThreadFactory implements ThreadFactory {
public final static ThreadFactory instance =
new DaemonThreadFactory();
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
}
That allows me to easily pass DaemonThreadFactory.instance
to the ExecutorService
, e.g.
ExecutorService pool = Executors.newFixedThreadPool(
4, DaemonThreadFactory.instance
);
or use it to easily start a daemon Thread from a Runnable
, e.g.
DaemonThreadFactory.instance.newThread(
() -> { doSomething(); }
).start();