开发者

Reentrant synchronization behavior with synchronized statements

开发者 https://www.devze.com 2023-03-01 05:08 出处:网络
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.

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    


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.


Yes you can, but this code won't compile: you are calling an instance method "method3" from a static method "method2". Other than that: if a thread has managed to aquire a lock in "method1" if will still have the lock in "method3".


Yes, the same thread can enter a synchronized block on the same lock multiple times. Be careful not to acquire other locks in a different order, otherwise you can cause a deadlock.


Though this code wont compile as already mentioned , lets consider the case that method2 is not static.A call from method1 to method2 and then to method3 is good example of reentrant synchronization.When a thread initiates, it creates a new stack with the run() at the bottom of the stack.Since the call to method1 comes from run() it is added in the stack above run() and then goes the method2 and method3 in the stack. Also, as the object lock is taken by method2 on the stack , the lock is maintained on all synchronized api called .The release of the lock is initiated by unwrapping the top most method (method3 in this case)in the stack till the actual api is reached which calls synchronize.

0

精彩评论

暂无评论...
验证码 换一张
取 消