0

From my understanding a Singleton is a single instance of a class that lasts throughout the span of an applications lifetime. However I've seen a few different implementations of the systems, but I'm always informed that they're wrong, flawed, etc. etc. I'm going to post the two that I see more commonly and I would like to hear opinions/fact based on which implementation is better and why. Implementations are compilable.

Implementation A:

public class Foo {
   private static Foo singelton;

   private Foo() {
       System.out.println("Bar");
   }

   public static Foo getSingleton() {
       if(singleton == null) singleton = new Foo();
       return singleton;
   }

   public static void main(String[] args) { 
       Foo.getSingleton();
   }
}

Implementation B:

public class Foo {
   private static final Foo singelton = new Foo();

   private Foo() {
       if(singelton != null) {
           throw new IllegalStateException("Singleton class was already constructed.");
       }
       System.out.println("Bar");
   }

   public static void main(String[] args) {
       // NOT REQUIRED
   }

}

You'll notice in Implementation B that the Singleton instance is final. Also, because of the static implementation the main(String[]) method never needs to construct an instance of this class.

Both Implementation A and B will yield the same results.

Opinions?

Hobbyist
  • 15,888
  • 9
  • 46
  • 98

1 Answers1

1

Hey you have shown two implementations, the second one is called early initialization and first one is called lazy initialization, as it is initializing the class on demand only. However your first initialization will fail in multi-threaded environment. You have to use double checked locking to secure your code. E. g. :

public class EagerSingleton {
    private static volatile EagerSingleton instance = null;

    // private constructor
    private EagerSingleton() {
    }

    public static EagerSingleton getInstance() {
        if (instance == null) {
            synchronized (EagerSingleton.class) {
                // Double check
                if (instance == null) {
                    instance = new EagerSingleton();
                }
            }
        }
        return instance;
    }
}

For morer details please check : http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/

Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
  • So from my understand (Before and after reading the link). Eager `(early)` initializing is the best way to go, especially if the class is required at runtime? Is this correct? – Hobbyist Apr 07 '15 at 04:27
  • but if the instance require more memory then It will remain live without usage. – Sachin Gupta Apr 07 '15 at 04:31