Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchonized

 
Karthik Gupta
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which one will have advantage synchonized method of sychronized block

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

public synchronized void method1(){
m.put("A",this);
}

public void method2(){
synchronized(this){
m.put("A",this);
}
}
}

Thanks

kathik
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is absolutely no difference between these two.
 
Balaji Akella
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Swamy
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic