• Post Reply Bookmark Topic Watch Topic
  • New Topic

Diff between the given four Synchronized blocks  RSS feed

 
Vidyasagar Guduru
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have some confusion on the synchronized method/block/lock, please some body explain in detail on when exactly the entire instance is locked and what is the exact diff between the below snippets.

1.
public synchronized void methodA(){
// code
}
2. public void methodA(){
synchronized(this)
{
//same code
}
}
3.
public void methodA(){
synchronized (new Singleton())//It is a global object for locking
{
// same code
}
}
4.
public void methodA(){
synchronized (new Object())
{
// same code
}
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One and two are identical in effect; no two threads can execute the method (or any other methods that synchronize on the same instance) at the same time.

Three and four are pointless; locking on an object that is created on the spot like that means that no other method call can try to lock that same object. Every call to the method will create and lock a new object, so any number of threads can call the method at the same time. There's no difference between three and four and a plain, ordinary unsynchronized method.
 
Vidyasagar Guduru
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply, I thought the same.
Regarding the the singleton, I put it wrong suppose the method is like this.

3.
public void methodA()
{

syncnronized(getSingleTonObject())//All threads are getting the same object lock
{
//Same code
}
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In that case, since all instances will share a single lock object, then no two threads can call that method on any instance of the class.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!