[concurrency-interest] An article example

Alexandru Popescu ☀ the.mindstorm.mailinglist at gmail.com
Sun Apr 29 21:22:23 EDT 2007


On 4/30/07, David Holmes <dcholmes at optusnet.com.au> wrote:
> Alex,
>
> They code the wait() in an "if" , instead of a "while" loop.
>
>      synchronized(lock) {
>          if (queue.isEmpty()) {
>             try {
>                lock.wait();
>             } catch (InterruptedException e) {
>                assert (false);
>             }
>          }
>          current = queue.removeFirst();
>       }
>
> So two consumers wait because it was empty. The producer does a notifyAll
> and so both consumers think there is work to do when there is only one item
> in the queue.
>

Darn... I don't know what a hell I was thinking :-). Thanks a lot David.

./alex
--
.w( the_mindstorm )p.

> Cheers,
> David Holmes
>
> > -----Original Message-----
> > From: concurrency-interest-bounces at cs.oswego.edu
> > [mailto:concurrency-interest-bounces at cs.oswego.edu]On Behalf Of
> > Alexandru Popescu ?
> > Sent: Monday, 30 April 2007 9:09 AM
> > To: userConcurrency
> > Subject: [concurrency-interest] An article example
> >
> >
> > Hi all!
> >
> > I was reading the PrintQueue example in this article:
> > http://www-128.ibm.com/developerworks/java/library/j-contest.html.
> > Later in the article there is the following comment:
> >
> > [quote]
> > [snip...] and suddenly you'll get a NoSuchElementException thrown by
> > LinkedList.removeFirst() in line 24. The bug lurks in the following
> > scenario:
> >
> >    1. Two consumer threads are started, find the queue to be empty,
> > and do wait().
> >    2. A producer enqueues a task and notifies both consumers.
> >    3. One consumer gets the lock, works the task, and leaves the queue
> > empty. It then releases the lock.
> >    4. The second consumer gets the lock (it can proceed because it was
> > notified) and tries to work a task, but now the queue is empty.
> > [/quote]
> >
> > Now this comment kind of confuses me because as far as I can say by
> > the end of step3, the queue is indeed empty and the 2nd consumer will
> > see this in the condition queue.isEmpty() so it will wait.
> >
> > Can you please explain what am I missing?
> >
> > many thanks in advance,
> >
> > ./alex
> > --
> > .w( the_mindstorm )p.
> > _______________________________________________
> > Concurrency-interest mailing list
> > Concurrency-interest at altair.cs.oswego.edu
> > http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>


More information about the Concurrency-interest mailing list