sree
sree

Reputation: 43

how to ensure only one instance of singleton class is created?

I have read the concepts of Singleton design pattern and understood that for making a class singleton we have to do the following steps :

1)Private constructor to restrict instantiation of the class from other classes.

2)Private static variable of the same class that is the only instance of the class.

3)Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.

So my class looks like this :

public class Singleton {

   private static Singleton singleton =new Singleton();;

   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ 
       System.out.println("Creating new now");
   }

   /* Static 'instance' method */
   public static Singleton getInstance( ) {
     return singleton;
   }
   /* Other methods protected by singleton-ness */
   public void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}

But here how we can ensure that only one instance of Singleton is created ? Suppose I have 2 classes Singletondemo1 and Singletondemo2. In Singletondemo1 , I am calling the getInstance() and craete an object. Same way I can do that in Singletondemo2 also.

So how we will ensure only object is created and also it is thread safe.

Upvotes: 2

Views: 3572

Answers (1)

In your example, no check ensures there is only one instance that exists in the global or required scope.

public class Singleton {

    private static Singleton instance;
    public String value;

    /* A private Constructor prevents any other
    * class from instantiating.
    */
    private Singleton(String value) {
        // The following code emulates slow initialization.
        // It also could initialize something during the singleton creation.
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        this.value = value;
    }

    /**
     * Checks if there is already a Singleton instance.
     * If not, creates a new instance and returns it.
     */
    public static Singleton getInstance(String value) {
        if (instance == null) {
            instance = new Singleton(value);
        }
        return instance;
    }

    /* Other methods protected by singleton-ness */
    public void demoMethod( ) {
        //
    }
}

Upvotes: 0

Related Questions