Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with Thread Interaction

 
Pradeep Bhat
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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
Posts: 225
Debian Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic