I want an object that will spawn a daemon thread that will continue to run for the lifetime of the process. Let's say, just for the sake of the argument, that it's a thread in an embedded system, and it waits to receive and handle commands on some diagnostic port. But, it could be anything really. The main idea is that it's watching something over a long period of time; It's not performing a sequence of tasks.
Common Java wisdom says, Never instantiate Thread, Use an ExecutorService instead. (E.g., see this answer) But what's the benefit? Using a thread pool as a means to create a single long-running thread seems pointless. How would it be any better than if I wrote this?
class Foobar {
public Foobar() {
this.threadFactory = Executors.defaultThreadFactory();
...
}
public Foobar(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
...
}
public void start() {
fooThread = threadFactory.newThread(new Runnable() { ... });
fooThread.setDaemon(true);
fooThread.start();
}
...
}
Note: this question seems similar to mine, but the answers only say how to use a thread pool, not why.