Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Synchonized

 
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
 
author and iconoclast
Posts: 24203
43
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is absolutely no difference between these two.
 
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
 
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.
 
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 ]
 
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.
 
Just let me do the talking. Ahem ... so ... you see ... we have this tiny ad...
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic