go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  What we can learn from Singleton Pattern -- Double-checked Locking Issue
 
Subject: What we can learn from Singleton Pattern -- Double-checked Locking Issue
Author: Alex_Raj
In response to: What we can learn from Singleton Pattern -- Code Efficiency
Posted on: 12/05/2013 11:41:55 PM


What's wrong with the example shown above then? Let's look at this piece:

        if(instance==null){
	    synchronized(Singleton.class){
                if(instance==null){
                    instance = new Singleton();
                }
            }
        }


It's well known "double-checked locking" trick. But is doesn't work for JDK prior to 1.5.0. The compiler optimization could mess it up by making the assignment of the new Singleton object before all its fields are initialized.

This is no longer an issue after JDK 1.5.0.


 

> On 12/05/2013 11:39:46 PM Alex_Raj wrote:


What's wrong with the example shown above this time? Nothing is wrong here, but it's just not efficient.

You might have noticed the cost of synchronization -- there will be an extra cycle to grab and release the sync lock each time to get the instance. Only the first time is really needed and the rest are just pure waste of time.

Here comes the variation to enter the sync block only once:

/**
 * Synchronized on block - double-checked locking
 */
public class Singleton 
{
    /* static field to ensure only one copy */
    private static Singleton instance;

    /* private constructor to prevent it from being instantiated from outside */
    private Singleton() {
    }

    /* public static method to ensure global point of access */
    public static Singleton getInstance() 
    {
        if(instance==null){
	    synchronized(Singleton.class){
                if(instance==null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public void sayHello() {
        System.out.println("Hello");
    }
}






References:

 


 
Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.