JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Explain Difference between synchronized block and method in Java Thread with example


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




/**
  * 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");
        }
    }
     
}

.