• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronized block doubt

 
archit thakur
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

As per my understanding, the difference between Synchronized method and Synchronized block is that in synchronized method...compiler doesn't allow any other thread to go in the method for a particular object...if some other thread is inside the same method for the same object but that object could be any object and in synchronized block..we specify that object for which the method call has to be synchronized

but if I try to run the following code,



output
{{{onethreetwo}
}
}

which was expected also

but for the following code:



output:
{one}
{two}
{three}

why the method is synchronized when the argument specified in the synchronized block is different from what is used in calling the method.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
archit thakur wrote:Hi,
As per my understanding, the difference between Synchronized method and Synchronized block is


A synchronized method is just syntactic sugar for a synchronized block. Declaring an instance method (non-static method) synchronized is the same as just putting synchronized (this) { } around the whole method body. Declaring a class method (static method) synchronized is the same as just putting synchronized (ThisClass.class) { } around the whole method body (where ThisClass is replaced by the actual class name, of course).

Syncing always does exactly the same thing: Obtains the object's lock, first waiting until it's released if some other thread currently holds it. As far as mutual exclusion goes, that's all it does.
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
archit thakur wrote:why the method is synchronized when the argument specified in the synchronized block is different from what is used in calling the method.

Well, technically, the method is not synchronized. It is being called from a synchronized block.

Now, in your synchronized block, you are synchronizing on 'callme', and this reference is referring to same object for all 3 threads. Since the synchronization is done on same object for all 3 threads, only one thread can enter in that block.

I hope this helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic