I’m using a thread that is continuously reading from a queue.
Something like:
public void run() {
Object obj;
while(true) {
synchronized(objectsQueue) {
if(objectesQueue.isEmpty()) {
try {
objectesQueue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
obj = objectesQueue.poll();
}
}
// Do something with the Object obj
}
}
What is the best way to stop this thread?
I see two options:
1 – Since Thread.stop() is deprecated, I can implement a stopThisThread() method that uses a n atomic check-condition variable.
2 – Send a Death Event object or something like that to the queue. When the thread fetches a death event, it exits.
I prefer the 1st way, however, I don’t know when to call the stopThisThread() method, as something might be on it’s way to the queue and the stop signal can arrive first (not desirable).
Any suggestions?
The
DeathEvent(or as it is often call, “poison pill”) approach works well if you need to complete all of the work on the queue before shutting down. The problem is that this could take a long time.If you want to stop as soon as possible, I suggest you do this
To stop the thread
tthat instantiated with thatrunmethod, simply callt.interrupt();.If you compare the code above with other answers, you will notice how using a
BlockingQueueandThread.interrupt()simplifies the solution.I would also claim that an extra
stopflag is unnecessary, and in the big picture, potentially harmful. A well-behaved worker thread should respect an interrupt. An unexpected interrupt simply means that the worker is being run in a context that the original programmer did not anticipate. The best thing is if the worker to does what it is told to do … i.e. it should stop … whether or not this fits with the original programmer’s conception.