Resync with synchronized agents

I have two methods in a java class that have a block of code that synchronizes using the same object. I understand that in a JAVA synchronization scheme, the locks received by the thread are reentrant. With this, I can safely say that the code below will not cause any problems 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 
+6
source share
4 answers

Yes you can, but this code will not compile: you call the instance method "method3" from the static method "method2". Besides this: if the thread managed to capture the lock in "method1", if it still blocks "method3".

+5
source

Yes, synchronized blocks are reentrant. ReentrantLock is also reentrant, and if you want to encode blocks yourself, you can use it instead, since it has more flexibility / functionality.

I would make sure that any lock is final If the lock object cannot be final, this is almost certainly an error (or a source of confusion)

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

+8
source

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

+4
source

Although this code will not compile, as already mentioned, consider the case where method2 is not static. A call from method1 to method2 and then to method3 is a good example of reentrant synchronization. When a thread is initiated, it creates a new stack with run () at the bottom of the stack. Since the call to method1 comes from run (), it is pushed onto the stack above run (), and then it passes to method2 and method3 to the stack. In addition, since the object is locked by method2 on the stack, the lock is saved on all called synchronized api. Lock allocation is triggered by deploying the topmost method (method3 in this case) on the stack until the actual api that causes the synchronization.

0
source

Source: https://habr.com/ru/post/886686/


All Articles