I implement long running thread in this way:
public class LongRunningWorker implements Runnable {
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
// get a job from threadsafe job queue and run it.
Job job = jobQueue_.removeJob();
execute(job);
TimeUnit.SECONDS.sleep(workerSleepSec_);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
LOGGER.info("runner quit");
// Clean up
cleanup();
}
}
}
In the main function I added them in a executor:
ExecutorService executor_ = Executors.newFixedThreadPool(numOfThreads);
for (int i = 0; i < num; ++i) {
executor_.submit(new LongRunningWorker(jobQueue));
}
It turns out the LongRunningWorker is not always running. After several hours executing, I found out all those LongRunningWorker exits. Why is it? If I want to make it always running, How to do that?
It seems that you don't understand the point of the ExecutorService: there is no need to "manually" keep those threads alive. The framework will do that for you.
In other words: the idea of that ExecutorService is that you simply continue to submit tasks into it. And the underlying implementation manages threads for you. And when you go for the fixed thread pool service, rest assured that you will always be running with the given count of threads.
Edit: given your comment - if your main focus is about "resources" that need to be managed along with the threads using them; then I see two options:
Edit: further thinking about your problem ... you should check if there aren't other problems (like uncaught exceptions) that cause your threads to stop. Maybe you could try catching for a wider range of exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With