It's not a secret anymore!
The moose likes Threads and Synchronization and the fly likes Problem with Thread Interaction Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Problem with Thread Interaction" Watch "Problem with Thread Interaction" New topic

Problem with Thread Interaction

Pradeep Bhat

Joined: Jan 12, 2008
Posts: 29
I was reading about Thread Interaction and came up with the following program that has a single producer and multiple consumer threads all working on a common 'queue' list. If the list is empty, the consumer threads have to wait till the queue is full. The produces fills the queue, notifies everyone and goes to sleep.


Is this code proper ?

Also the output appears as follows



The consumer thread should wait in case the queue is empty and wait for the notification. Then why is the index out of bound exception thrown ?
Carey Evans
Ranch Hand

Joined: May 27, 2008
Posts: 225

The simplest solution would be to use a LinkedBlockingQueue<String> instead of a List. But to answer your question...

When the producer calls notifyAll(), every waiting consumer wakes up. One of them gets the lock, empties the list, and releases the lock. Then another gets the lock, tries to empty the list, and fails. Finally, the third consumer does the same.

Making this worse is that wait() can return without notifyAll() being called at all.

To do this properly, you can use a while loop instead of an if statement:
Or use a BlockingQueue:
[ July 29, 2008: Message edited by: Carey Evans ]
I agree. Here's the link:
subject: Problem with Thread Interaction
It's not a secret anymore!