Monday, February 20, 2023

Difference between synchronized block and method in Java? Thread Example

Synchronized block and synchronized methods are two ways to use synchronized keywords in Java and implement mutual exclusion on critical sections of code. Since Java is mainly used to write multi-threading programs,  which present various kinds of thread-related issues like thread-safety, deadlock, and race conditions, which plagues into code mainly because of poor understanding of the synchronization mechanism provided by the Java programming language. Java provides inbuilt synchronized and volatile keywords to achieve synchronization in Java. The main difference between the synchronized method and the synchronized block is a selection of locks on which critical section is locked.


A synchronized method depending upon whether it's a static method or non-static locks on either class level lock or object lock. A class level lock is one for each class and represented by class literal e.g. Stirng.class. The object-level lock is provided by a current object like this instance, You should never mix static and non-static synchronized methods in Java.

On the other hand synchronized block locks on monitor evaluated by expression provided as a parameter to synchronized block. In the next section, we will see an example of both synchronized method and synchronized block to understand this difference better.

Difference between synchronized block and method in Java? Thread Example



Difference between synchronized method vs block in Java

Difference between synchronized method and synchronized block in Java with exampleHere are Some more differences between synchronized method and block in Java-based upon experience and syntactical rules of synchronized keyword in Java. Though both block and method can be used to provide the highest degree of synchronization in Java, the use of synchronized block over method is considered a better Java coding practice.




1. Scope of lock
One significant difference between the synchronized method and block is that Synchronized block generally reduces the scope of the lock. As the scope of a lock is inversely proportional to performance, it's always better to lock only a critical section of code. 

One of the best examples of using a synchronized block is double-checked locking in the Singleton pattern where instead of locking the whole getInstance() method we only lock the critical section of code that is used to create the Singleton instance. This improves performance drastically because locking is only required one or two times.

2. Control over the lock
Synchronized blocks provide granular control over a lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand, the synchronized method always locks either on the current object represented by this keyword or class level lock, if it's a static synchronized method.


3. NullPointerExcpetion
Synchronized block can throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null, which is not the case with synchronized methods.

4. Lock Acquisition
In the case of the synchronized method, the lock is acquired by a thread when it enters the method and is released when it leaves the method, either normally or by throwing Exception.

On the other hand in the case of the synchronized block, the thread acquires a lock when they enter the synchronized block and release it when they leave the synchronized block. 

You can also see these Java Multithreading and Concurrency courses to learn more about monitor, lock, and concurrency. 

Synchronized method vs synchronized block Example in Java



Synchronized method vs synchronized block Example in Java

Here is an example of a sample class that shows on which object synchronized method and block are locked and how to use them :

/**
  * Java class to demonstrate the use of synchronization method and block in Java
  */

public class SycnronizationExample{
 
 
    public synchronized void lockedByThis(){
        System.out.println(" This synchronized method is locked by current" instance of object i.e. this");
    }
 
    public static synchronized void lockedByClassLock(){
        System.out.println("This static synchronized method is locked by class level lock of this class i.e. SychronizationExample.class");

    }
 
    public void lockedBySynchronizedBlock(){
        System.err.println("This line is executed without locking");
     
        Object obj = String.class; //class level lock of Stirng class
     
        synchronized(obj){
            System.out.println("synchronized block, locked by lock represented using obj variable");
        }
    }
     
}


That's all on the difference between synchronized method and block in Java. Favoring synchronized block over method is one of the Java best practices to follow as it reduces the scope of lock and improves performance. 

On the other hand, using the synchronized method are rather easy but it also creates bugs when you mix non-static and static synchronized methods, as both of them are locked on different monitors and if you use them to synchronize access of shared resource, it will most likely break.


Other Java multi-threading tutorials you may like

5 comments:

  1. Synchronized method is overkill, instead try to avoid synchronization from start.

    ReplyDelete
  2. A good insight. Thank You!

    ReplyDelete
  3. One more advantage is using synchronized block: You can acquire lock on any object which you specify as synchronized(Object) where as in synchronized method it looks like synchronized(this).

    ReplyDelete
    Replies
    1. That's really a significant differnece and can dictat the use of synchornized block.

      Delete
  4. Kya likha hain maja aa gaya miya

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.