I have a MyThread object which I instantiate when my app is loaded through the server, I mark it as a Daemon thread and then call start()
on it. The thread is m
If you're using a scheduled executor, you can provide a ThreadFactory. This is used to create new Threads, and you can modify these (e.g. make them daemon) as you require.
EDIT: To answer your update, your ThreadFactory
just needs to implement newThread(Runnable r)
since your WebRunnable
is a Runnable
. So no real extra work.
Just to complement with another possible solution for completeness. It may not be as nice though.
final Executor executor = Executors.newSingleThreadExecutor();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
executor.shutdownNow();
}
});
Check out the JavaDoc for newSingleThreadScheduledExecutor(ThreadFactory threadFactory)
It would be implemented something like this:
public class MyClass {
private DaemonThreadFactory dtf = new DaemonThreadFactory();
private ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor(dtf);
// ....class stuff.....
// ....Instance the runnable.....
// ....submit() to executor....
}
class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
}