Wednesday, January 16, 2013

Difference between synchronized block and method in Java

Synchronized block and synchronized methods are two ways to use synchronized keyword in Java and implement mutual exclusion on critical section 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 synchronization mechanism provided by Java programming language. Java provides inbuilt synchronized and volatile keyword to achieve synchronization in Java. Main difference between synchronized method and synchronized block is selection of lock on which critical section is locked. Synchronized method depending upon whether its a static method or non static locks on either class level lock or object lock. Class level lock is one for each class and represented by class literal e.g. Stirng.class. Object level lock is provided by current object e.g. this instance, You should never mix static and non static synchronized method in Java.. On the other hand synchronized block locks on monitor evaluated by expression provided as parameter to synchronized block. In next section we will see an example of both synchronized method and synchronized block to understand this difference better.

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 highest degree of synchronization in Java, use of synchronized block over method is considered as better Java coding practices.

1) One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code. One of the best example of using synchronized block is double checked locking in Singleton pattern where instead of locking whole getInstance() method we only lock critical section of code which is used to create Singleton instance. This improves performance drastically because locking is only required one or two times.

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

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

4) In case of synchronized method, lock is acquired by thread when it enter method and released when it leaves method, either normally or by throwing Exception. On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.

Synchronized method vs synchronized block Example in Java
Here is an example of  sample class which shows on which object synchronized method and block are locked and how to use them :

/**
  * Java class to demonstrate 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 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 scope of lock and improves performance. On the other hand using 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

3 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

Java67 Headline Animator