• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Problem with Thread Interaction

 
Ranch Hand
Posts: 31
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Ranch Hand
Posts: 225
Eclipse IDE Debian Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Time is mother nature's way of keeping everything from happening at once. And this is a tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic