Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reentrant synchronization behavior with synchronized statements

Tags:

java

I have two methods in a java class that both have a block of code that synchronize using the same object. I understand that in the JAVA synchronization scheme locks acquired by a thread are reentrant. With this can i safely say the below piece of code will not cause any issues in all cases?

public class Someclass  
{  
  private static final Object LCK_OBJ = new Object();  
  //.....

  publc void method1()  
  {  
    //some code....  
    synchronized(LCK_OBJ)  
    {  
        //some sychronized code.  
        method2(..);  
    }  
    //some more code....  
  }  

  protected static final void method2(..)  
  {  
      Someclass ref = null;  
      //some code which gets different other references of SomeClass in a loop....  
      ref.method3(..);  
  }  

  publc void method3()  
  {  
    //some code....  
    synchronized(LCK_OBJ)  
    {  
      //some sychronized code.  
    }  
    //some more code....  
  }  

}//end of class    
like image 561
Muthu Avatar asked Apr 26 '11 08:04

Muthu


1 Answers

Yes, synchronized blocks are reentrant. ReentrantLock is also reentrant and if you want to code the blocks yourself, you might want to use that instead as it has more flexibiliy/functionality.

I would make sure any lock is final If a lock object cannot be final, it is almost certainly a bug (or a source of confusion)

For comparison purposes, not all locks in Java are reentrant. FileLock is not as it passes the request directly to the OS.

like image 144
Peter Lawrey Avatar answered Oct 21 '22 05:10

Peter Lawrey