Re: Java Tutorial, Concurrency trail
On 2/17/2011 4:53 AM, Ian wrote:
Hi all,
I have a question regarding the Java tutorial, concurrency trail, which
contains an example of deadlock between two bowing friends.
http://download.oracle.com/javase/tutorial/essential/concurrency/deadlock.html
There is a forum question on this subject, but I don't believe the OPs
question is answered properly:
http://forums.oracle.com/forums/thread.jspa?threadID=1140695&tstart=120.
I have observed the same results as the OP, but I can't reconcile what
happens with any of the tutorial material (the code is pretty much
posted into the tutorial without detailed comment). Is anyone here
familiar with that code?
No, but it is a quite readable, simple example of a classic problem, so
I'm going to comment anyway.
As far as I can tell, alphonse's thread (by this I mean the first one)
grabs the default monitor for the synchronized bow method, and gaston's
thread (ie the second one) should be blocked, so how does gaston's
thread acquire the lock at all?
Monitors are not associated with methods but with objects. A
synchronized non-static method uses the monitor for the object that its
"this" references. I think the main problem with your analysis is
thinking in terms of *the* monitor for the bow method.
The example code uses two monitors, each associated with one of the two
Friend objects. For convenience, I'm going to call them MonitorA and
MonitorG. I'll also call the two threads ThreadA and ThreadG.
Consider the following sequence:
ThreadA calls Alphonse's bow method, locking MonitorA
ThreadG calls Gaston's bow method, locking MonitorG
ThreadA, from Alphonse's bow method, and therefore still holding
MonitorA, calls Gaston's bowBack method. The method is synchronized on
MonitorG, currently held by ThreadG, so ThreadA is blocked.
ThreadG, from Gaston's bow method, and therefore still holding MonitorG,
calls Alphonse's bowBack method. It is synchronized on MonitorA,
currently held by ThreadA, so ThreadG is blocked.
Patricia