| Author |
Shutting down consumer thread when producer is finished
|
Theodore David Williams
Ranch Hand
Joined: Dec 21, 2009
Posts: 102
|
|
I am using an ArrayBlockingQueue.
A producer loops over some data and inserts into the queue until end of data.
The consumer 'takes' from the queue until it receives a shutdown(i.e. the producer is finished) and the queue is empty(i.e. it is done processing all entires in the queue)
Producer pseudo code
Consumer pseudo code
This works as I would expect except for when I call shutdown in the producer I have no idea how long it will take the consumer to process what was left in the queue and actually finish.
Is there a good wait to wait/block on the shutdown call such that when that call returns I know the consumer thread is finished?
|
 |
Jelle Klap
Bartender
Joined: Mar 10, 2008
Posts: 1409
|
|
You could use an ExecutorService to fire up and shutdown the producer and consumer. HAve a look at its API, specifically the shutdown() / shutdownNow() and awaitTermination() methods.
An other way would be to use a "poison pill". When the producer is finished have it produce an object that is recognizable to the consumer as a shutdown indicator. That can get a bit involved though, when you have multiple producers and consumers hooked up to the same queue.
|
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
|
 |
 |
|
|
subject: Shutting down consumer thread when producer is finished
|
|
|