[concurrency-interest] An article example
dcholmes at optusnet.com.au
Tue May 1 15:46:37 EDT 2007
Szabolcs Ferenczi wrote:
> I am afraid what can even be more confusing is the suggestion in the
> article for fixing the bug:
> "(By the way, do you know how to fix the bug? Careful: replacing the
> notifyAll() with notify() solves the problem in this scenario but will
> fail on others!)"
They aren't suggesting a fix, they are telling you that although changing to notify() appears to be a fix, it only actually corrects this one scenario. It was poor form for them to not actually tell you what the real fix was - though I presume they wanted you to run the tool and have it tell you.
For any reader wondering why changing the notifyAll() to a notify() would help the immediate problem but not actually fix the bug: the notify() would only wake one of the consumers and so the second would remain waiting until a second notification that would indicate another item has been produced - hence two consumers would not try to consume one item. But there is still a bug present because - in general - between being notified that there is an item and actually reacquiring the lock to go and grab that item, another consumer could have come along and taken the item already. Hence you must always re-check the condition you were waiting for after the wait() returns - hence the canonical form for using wait() is:
> Let me remark that in the original monitor construction as suggested
> by Hoare, the if check is correct before the wait statement. In Java
> it is not correct. More confusion for a lot of people.
It isn't correct with Brinch-Hansen monitors either. So I don't see this as a source of confusion for Java programmers in general - depending on what classes you took your exposure to any kind of monitor concept could be very limited.
The reason it is correct with Hoare monitors is that the "notifier" (which isn't explicit) hands-off the monitor to the waiter, so there is no possibility of the condition changing in the mean-time. While semantically this is a nice model the performance implications are not good due to the forced context switching.
For anyone interested in the wide-range of monitor "styles" available I'd recommend the paper by Peter Buhr et al: "Monitor Classification"
Buhr's uC++ language is also very interesting. There are various papers I believe, but if you want lots of gory detail then check out the book:
More information about the Concurrency-interest