Friday, September 28, 2012

What is the difference between a synchronized method and synchronized block in Java?

First, we write the following code for synchronized method. 
Non-static synchronized method:
public synchronized void method(){
            System.out.println ("non-static synchronized method.");
As per synchronization only one thread will process synchronized method at a time. That means, when one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object and it is equivalent to following code as it blocks on its object.
Non-static synchronized block:
public void method(){
            synchronized (this) {
                  System.out.println("non-static synchronized block.");

And for static,
Static synchronized method:
      public static void method() {
            System.out.println("static synchronized method.");

And it is equivalent to,  
Static synchronized block:
public void method(){
            synchronized (SynchronizationDemo.class) {
                  System.out.println("static synchronized block.");
Here, JVM converts the synchronized methods to synchronized blocks implicitly. Synchronized blocks are more convenient to specify synchronization to specific statements or objects (not null) like following.
      public void method() {
                  System.out.println("synchronization on specific object.");
            System.out.println("you can leave thread safe statements from block.");

No comments:

Post a Comment