I'm having some trouble wrapping my head around the concept of synchronized blocks in Java. I feel I have understood synchronized methods well enough. So I thought of an analogy to help me understand synchronized blocks in terms of synchronized methods. Please let me know if this equivalence that I have proposed is correct. Also, I have only mentioned this for a non-static synchronized block for now. However, points on static synchronzied blocks are also welcome.
public void method()
{
//code snipppet A
synchronized(objRef)
{
//code snipppet B
}
//code snipppet C
}
Is equivalent to
public void method() {
//code snippet A
objRef.sync_method();
//code snippet C
}
In the class of objRef:
public synchronized void sync_method() {
//code snippet B
}
This analogy is based on the logic that synchronized blocks behave just as synchronized methods do. Meaning that once a thread acquires a lock on the monitor, it does not allow other threads to interfere in its execution. The thread relinquishes control only once it has finished executing the entire synchronized method.