Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized block and monitor objects

Tags:

java

Hi can someone explain if the in the following code the synchronized code will restrict access to the threads. If yes how is it different from, if we have used "this" as a monitor object instead of "msg".

public void display(String msg)    
{    
    synchronized(msg)    
    {    
        for(int i=1;i<=20;i++)    
          {    
               System.out.println("Name= "+msg);    
          }  
    }   
}
like image 744
Vibhor Avatar asked Apr 05 '12 19:04

Vibhor


2 Answers

synchronized(this)

means only locking on this object instance. If you have multiple threads using this object instance and calling this method, only one thread at a time can access within the synchronized block.

synchronized(msg) 

means the locking is base on the msg string. If you have multiple threads using this object instance and calling this method, multiple threads can access within this synchronized block if the msg are different instance. Beware of how Java deal with String equality to avoid the surprising effect tho.

like image 130
evanwong Avatar answered Oct 02 '22 02:10

evanwong


The method you wrote will block only if two threads will invoke this method with the exact same msg object.

If you synchronize on this then it only one thread will be able to invoke the method at a given time.

like image 34
Udi Cohen Avatar answered Oct 02 '22 00:10

Udi Cohen