[concurrency-interest] Are synchronized methods safer than synchronized blocks?

Yao Qi qiyaoltc at gmail.com
Mon Dec 14 21:22:52 EST 2009

On Mon, Dec 14, 2009 at 4:34 PM, Will McQueen <willmcqueen at yahoo.com> wrote:

I agree with you on your understandings, but I have some different
thought on your conclusions....
> If the above is true, then I would conclude that:
> 1) I should favor synchronized methods over synchronized blocks, especially in critical systems where deadlock must absolutely be avoided.

I don't think deadlock can be avoided absolutely....
Here is an example (Deadlock.java in attachment) on two classes using
synchronized methods only however, deadlock is still there.  I run
Deadlock.java in MulticoreSDK
(http://www.alphaworks.ibm.com/tech/msdk), and find one deadlock in
it, shown in deadlock.png.

> 2) By extension, I should favor synchronized methods over Java 1.5's Lock class (where the Lock object's unlock() method must be called in a finally clause that is also susceptible to the '2nd exception' issue).

IMO, Java 5's Lock classes are introduced for performance and
flexibility.  JUC Lock is efficient than Object monitor in some cases,
and Lock is more and more used to replace Object monitor in order to
improve scalability....
I agree that there is a risk on "lock leak" problem, as you mentioned.
 Since there are some data flow tools can analyze "lock leak" problem
statically, it is not a big problem.

Yao Qi <qiyaoltc AT gmail DOT com>    GNU/LinuxDeveloper
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Deadlock.java
Type: text/x-java
Size: 780 bytes
Desc: not available
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20091215/853f0d3e/attachment.bin>

More information about the Concurrency-interest mailing list