James Bond James Bond - 3 months ago 25
Java Question

Simplification of synchronized block in Java

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

//code snipppet B
//code snipppet C

Is equivalent to

public void method() {
//code snippet A
//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.


You should notice that there are tow types of synchronized block in Java (object synchronize and class synchronize). There are two synchronized methods (static and non-static methods) and their equivalent synchronized blocks (Class and Object Synchronized blocks respectively). assume we have:

class MyClass{
public static void synchronized syncNonStaticMethod(){...}
public void synchronized syncStaticMethod(){...}

MyClass objRef = new MyClass();

1. Object Synchronization:

public void method() {synchronized(objRef) { ... }}

Is equivalent to

 public void method() {objRef.syncNonStaticMethod();}

2. Class Synchronization:

 public void method() {synchronized(MyClass.class) { ... }}

Is equivalent to

   public void method() {objRef.syncStaticMethod();}