This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes ArrayBlockingQueue - can't put(null) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "ArrayBlockingQueue - can Watch "ArrayBlockingQueue - can New topic

ArrayBlockingQueue - can't put(null)

Carey Brown
Ranch Hand

Joined: Nov 19, 2001
Posts: 174

I'm using a ArrayBlockingQueue to queue up input from a pipe. When I reach the end of the pipe input (as evidenced by the returning of a null) I want to mark the end of the queue with something that the consumer can take() and determine that there will be no more data to follow. I wanted to put a null on the queue but then I get a NullPointerException in the library. As a work-around I'm adding an empty string ("") which the consumer then detects. Currently an empty string doesn't conflict with any real data so this works, but I don't feel that this is a proper long term solution. Any other ideas???

Thanks in advance,
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

It is typical to put a 'TerminalObject' into the Queue when the end of Production has occurred. It is even described in BlockingQueue API. The best value for the termination signal depends on what you are putting through the Queue. If your Queue is a BlockingQueue<String> then using an empty String as a termination value is as good as any.

Another option would be to have a separate thread that waits for the producer to end, and when it does, interrupts the consumer (un-blocking it) and signals for it to stop.

Carey Brown
Ranch Hand

Joined: Nov 19, 2001
Posts: 174

Thanks for the reply Steve, you helped me solidify the concept in my mind.
I agree. Here's the link:
subject: ArrayBlockingQueue - can't put(null)