File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Synchonized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Synchonized" Watch "Synchonized" New topic


Karthik Gupta

Joined: Feb 17, 2005
Posts: 3
Which one will have advantage synchonized method of sychronized block

public class Test {
HashMap m = new HashMap();

public synchronized void method1(){

public void method2(){


Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

There is absolutely no difference between these two.

[Jess in Action][AskingGoodQuestions]
Balaji Akella
Ranch Hand

Joined: Oct 29, 2003
Posts: 35
Synchronizing a method would mean acquiring a lock to an entire method - and in the cases where synchronizing a block of code is sufficient, it might be a over-kill to synchronize an entire method. The feature for synchronizing a block code will provide the additional flexibility for limiting this process, to a code segment, instead of to an entire method.


In the morning there is hope; in the afternoon, fulfillment; in the evening, memory; at night, peace.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
In the two cases shown the lock is being aquired on the 'this' instance of the Test class. So I think Ernest is right, there is no difference here.
MK Barman

Joined: Dec 14, 2004
Posts: 3
Yes, Ernest is right.
weather you synchronize the method or a block of code inside the method but the monitor is associated with the current instance.
[ February 17, 2005: Message edited by: MK Barman ]
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
One small difference is that, if the method is declared synchronized, then that can be seen in the Javadoc. Whereas synchronisation within the method body does not automatically appear in the Javadoc. The run-time behaviour is the same, though.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I agree. Here's the link:
subject: Synchonized
jQuery in Action, 3rd edition