Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble with long running thread implementation

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?

like image 958
qqibrow Avatar asked Sep 04 '26 19:09

qqibrow


1 Answers

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:

  1. Instead of using the ExecutorService framework you do your complete own management implementation (doesnt sound like a great idea, does it)
  2. You make sure that your tasks can request "free" resources: meaning you keep the ExecutorService, but add some own code to manage the resources the tasks will need to their job independent of the ExecutorService threads.

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.

like image 105
GhostCat Avatar answered Sep 06 '26 11:09

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!