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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With