Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

后端 未结 23 2297
北荒
北荒 2020-11-22 04:29

Can any one tell me the advantage of synchronized method over synchronized block with an example?

23条回答
  •  暖寄归人
    2020-11-22 04:51

    I suppose this question is about the difference between Thread Safe Singleton and Lazy initialization with Double check locking. I always refer to this article when I need to implement some specific singleton.

    Well, this is a Thread Safe Singleton:

    // Java program to create Thread Safe 
    // Singleton class 
    public class GFG  
    { 
      // private instance, so that it can be 
      // accessed by only by getInstance() method 
      private static GFG instance; 
    
      private GFG()  
      { 
        // private constructor 
      } 
    
     //synchronized method to control simultaneous access 
      synchronized public static GFG getInstance()  
      { 
        if (instance == null)  
        { 
          // if instance is null, initialize 
          instance = new GFG(); 
        } 
        return instance; 
      } 
    } 
    

    Pros:

    1. Lazy initialization is possible.

    2. It is thread safe.

    Cons:

    1. getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.

    This is a Lazy initialization with Double check locking:

    // Java code to explain double check locking 
    public class GFG  
    { 
      // private instance, so that it can be 
      // accessed by only by getInstance() method 
      private static GFG instance; 
    
      private GFG()  
      { 
        // private constructor 
      } 
    
      public static GFG getInstance() 
      { 
        if (instance == null)  
        { 
          //synchronized block to remove overhead 
          synchronized (GFG.class) 
          { 
            if(instance==null) 
            { 
              // if instance is null, initialize 
              instance = new GFG(); 
            } 
    
          } 
        } 
        return instance; 
      } 
    } 
    

    Pros:

    1. Lazy initialization is possible.

    2. It is also thread safe.

    3. Performance reduced because of synchronized keyword is overcome.

    Cons:

    1. First time, it can affect performance.

    2. As cons. of double check locking method is bearable so it can be used for high performance multi-threaded applications.

    Please refer to this article for more details:

    https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples/

提交回复
热议问题