Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • how to differentiate synchronized block and synchronized method in Java

    • 0
    • 2
    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 2.89k
    Comment on it

    The synchronization is the mechanism by which we can control multiple threads to access the shared resources. Without synchronization, it is possible for one thread to modify a shared resource while another thread is in the process of using or updating that resource.

    There are two ways to use Syncronized keyword in java:

    1. Synchronized method
    2. Synchronized block

    With a synchronized method, the lock is obtained for the duration of the entire method. With synchronized blocks you can specify exactly when the lock is needed.

    Difference between synchronized method vs block in Java

    1)Scope of lock is reduced by Synchronized block. As scope of lock is inversely proportional to performance, that's why it's always better to lock only critical section of the code. 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.

    /**
    * Singleton pattern example with Double checked Locking
    */
    public class DoubleCheckedLockingSingleton{
         private volatile DoubleCheckedLockingSingleton INSTANCE;
    
         private DoubleCheckedLockingSingleton(){}
    
         public DoubleCheckedLockingSingleton getInstance(){
             if(INSTANCE == null){
                synchronized(DoubleCheckedLockingSingleton.class){
                    //double checking Singleton instance
                    if(INSTANCE == null){
                        INSTANCE = new DoubleCheckedLockingSingleton();
                    }
                }
             }
             return INSTANCE;
         }
    }
    2) In case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block. On the other hand in case of synchronized method, lock is acquired by thread when it enters method and released when it leaves method, either normally or by throwing Exception.

    Synchronized method vs synchronized block Example in Java
    Following is sample class which shows how to use synchronized method and block and on which object are locked as Synchronized method and synchronized block:
    /**
      * Java class to demonstrate use of synchronization method and block in Java
      */
    public class SycnronizationExample{
    
    
        public synchronized void lockedByThis(){// blocks "this" from here.... 
            System.out.println(" This synchronized method is locked by current" instance of object i.e. this");
        }// to here
    
        public static synchronized void lockedByClassLock(){// blocks "this" from here.... 
            System.out.println("This static synchronized method is locked by class level lock of this class i.e. SychronizationExample.class");
    
        }//to here
    
        public void lockedBySynchronizedBlock(){
            System.out.println("This line is executed without locking");
    
            Object locker = String.class; //class level lock of String class
    
            synchronized(locker){// blocks "this" from here.... 
                System.out.println("synchronized block, locked by lock represented using locker variable");
            }//to here
        }
    
    }
    

    Reference

    http://java67.blogspot.in/2013/01/difference-between-synchronized-block-vs-method-java-example.html

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: