views:

83

answers:

2

I have a consumer thread taking elements from a LinkedBlockingQueue, and I make it sleep manually when it's empty. I use peek() to see if the queue empty because I have to do stuff before sending the thread to sleep, and I do that with queue.wait().


So, when I'm in another thread and add()an element to the queue, does that automatically notify the thread that was wait()ing on the queue?

A: 

I tried to test this, but I'm unable to wait() on the queue without synchronizing on it (IllegalMonitorStateException otherwise). When one thread is wait()ing, it seems to block another thread from add()ing?

Lauri Lehtinen
That's because it implements the method in terms of `offer(element)` and doesn't need to do so itself; the other method *does* notify.
Donal Fellows
@Donal Fellows you are correct, I was a little too quick to post my initial answer .. sorry.
Lauri Lehtinen
+1  A: 

Yes it does. Or rather, it does using a more-efficient internal lock object and not the outer queue object's lock; if you want to sleep until something arrives in the queue, do a blocking take(). (If you have other things to do while waiting, consider whether a blocking queue is the correct way of receiving messages from elsewhere.)

Donal Fellows
It actually has two locks internally, one handling notification of the queue-empty case and the other of the queue-full case. They're `private` — with good reason — so use the API as it is meant to be used.
Donal Fellows