Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Shutting down consumer thread when producer is finished  RSS feed

 
Theodore David Williams
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!