I have three worker threads from main thread. Main thread puts objects into BlockingQueue. if queue does not have enough data, lets say only one object. Other two threads keep waiting state. How to i signal those other two waiting threads (because of call to queue.take()) to terminate?
one way to do this would be pass last dirty object on queue to have other stale threads to read and terminate. Is there any other elegant solution available?
public void run() {
if (log.isInfoEnabled()) {
log.info("Entering method 'run' " + this.getName());
}
try {
while (!noMoreData || !queue.isEmpty()) {
String data = queue.take();
...
...
doSomething();
}
if (log.isInfoEnabled()) {
log.info("noMoreData =" + noMoreData + ", queue empty=" + queue.isEmpty() + "....Terminating thread..." + this.getName());
}
} catch (InterruptedException ie) {
log.error(ie);
} finally {
//DONE SIGNAL
doneSignal.countDown();
log.info(this.getName() + " finished.");
}
}
You should use an ExecutorService using your configured queue (size and datastructure).
You then have a shutdown message (Runnable) that you submit to the executorservice which calls #shutdown(). Just submit that message last on the queue.
This method is very scalable because you can replace the executorservice wih a true message queue.