java - Stop all threads in a custom thread pool (like shutting down) -


in java library thread pool implementations, shutting down pool means:

-stop accepting new tasks

-previously submitted tasks executed

-all pool threads terminated

regarding last point, how stop pool thread potentially try take new task, after has been stopped?

my threads (in java pseudo code):

public void run() {   while(!isstopped) {     task task = taskqueue.take(); //line1     task.run(); //line2   } } 

and have method stop:

public synchronized void stop(){   isstopped = true;   this.interrupt(); } 

in thread pool class, have method stop:

public synchronized void shutdown(){   this.isshutdown = true; //to stop whole pool   for(poolthread thread : threads)     thread.stop(); } 

the point is, if thread reaches line 1, isstopped false, @ same moment set true pool class. how remember should stop thread again? calling interrupt suffice?

send shutdown messages through task queue:

static task stop = // 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 number of shutdown messages in queue equal number of threads, once work completed, threads each take shutdown message , shut down. (note don't need care thread gets shutdown message.)


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -