This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Shutting down consumer thread when producer is finished Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Shutting down consumer thread when producer is finished" Watch "Shutting down consumer thread when producer is finished" New topic
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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Shutting down consumer thread when producer is finished
 
Similar Threads
Producer Consumer Controller
Sun tutorial Producer/Consumer
Shutdown Threadpoolexecutor when queue is empty[SOLVED]
Multithreaded Example... Where to put WAIT() , NOTIFY() advise please
multithreading the wait method