Reputation: 1109
In Java library thread pool implementations, usually shutting down a pool means:
-stop accepting new tasks
-previously submitted tasks are executed
-all pool threads are terminated
Regarding the last point, how would you stop a pool thread that could potentially try to take a new task, after it has been stopped?
My threads do something like this (in java pseudo code):
public void run() {
while(!isStopped) {
Task task = taskQueue.take(); //line1
task.run(); //line2
}
}
and have a method stop:
public synchronized void stop(){
isStopped = true;
this.interrupt();
}
In my thread pool class, I have a method stop:
public synchronized void shutdown(){
this.isShutdown = true; //to stop the whole pool
for(PoolThread thread : threads)
thread.stop();
}
The point is, if a thread reaches line 1, isStopped was false, but at that same moment it could be set to true by the pool class. How do I remember that I should stop the thread again? Does calling interrupt suffice?
Upvotes: 0
Views: 1434
Reputation: 281843
Send the shutdown messages through the task queue:
static Task stop = // some special value
public void run() {
while (true) {
Task task = taskQueue.take();
if (task == stop) {
break;
}
task.run();
}
}
and in shutDown
:
public synchronized void shutdown(){
if (isShutdown) {
return;
}
this.isShutdown = true;
for(PoolThread thread : threads) {
taskQueue.put(PoolThread.stop);
}
}
With a number of shutdown messages in the queue equal to the number of threads, once all work is completed, the threads will each take a shutdown message and shut down. (Note that we don't need to care about which thread gets which shutdown message.)
Upvotes: 1