Synchronized block and monitor objects

Go To StackoverFlow.com

5

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);    
          }  
    }   
}
2012-04-05 19:35
by Vibhor
See http://stackoverflow.com/questions/574240/synchronized-block-vs-synchronized-metho - Matt Ball 2012-04-05 19:37
Well ... in one case, you're using the passed in Object's monitor. In the other ... you're using the instance's monitor - Brian Roach 2012-04-05 19:39


13

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.

2012-04-05 19:42
by Udi Cohen


6

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.

2012-04-05 19:43
by evanwong
+1 for mentioning the effect of java Objects equalit - vikki_logs 2014-09-02 10:01


0

if the in the following code the synchronized code will restrict access to the threads

Yes. The block cannot be invoked concurrently more then once on the same String object [and actually, all blocks which are syncrhonized on this String object].

how is it different from, if we have used "this" as a monitor object instead of "msg"

synchronized(this) prevents concurrent access to all blocks by the same object, in this case, the object that is the this of the method, will not be able to go into the synchronised block twice.

for example [using java-like pseudo code]:

s1 = s2;
Thread1:
MyObject o = new MyObject();
o.display(s1);
Thread2:
MyObject o = new MyObject();
o.display(s2);

The current method will not allow the block to be invoked concurrently by Thread1 and Thread2

However:

MyObject o = new MyObject();
Thread1:
o.display("s1");
Thread2:
o.display("s2");

Will not show blocking behavior between them - the monitor is catched by each "s1" and "s2" without disturbing each other.

2012-04-05 19:44
by amit
Ads