Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding singleton design pattern

I was exploring the singleton design pattern, I have developed a class...

public class SingletonObject {
  private static SingletonObject ref;       
  private SingletonObject () { //private constructor
  }     
  public static synchronized SingletonObject getSingletonObject() {
    if (ref == null)
      ref = new SingletonObject();
    return ref;
  } 

  public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException ();
  }
}

but synchronization is very costly , so I move to new design of eagerly created instance rather than a lazily created one..

public class Singleton {
  private static Singleton uniqueInstance = new Singleton();
  private Singleton() {
  }
  public static Singleton getInstance() {
    return uniqueInstance;
  }
}

But please advise me how the second design is advantage over the previous design..!!

like image 484
dghtr Avatar asked Jan 17 '23 21:01

dghtr


2 Answers

Josh Bloch recommends using an enum:

   public enum Foo {
       INSTANCE;
   }

For an explanation, see his Effective Java Reloaded talk at Google I/O 2008.

In summary:

"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

like image 86
Amir Afghani Avatar answered Jan 20 '23 16:01

Amir Afghani


As you stated, the second solution avoids synchronization costs. It is also simpler and cleaner, so easier to read and maintain. It has a little problem though: you miss a final qualifier for private static Singleton uniqueInstance, which means that it may not be guaranteed to be thread safe in a concurrent environment (although in this concrete case I don't think this would cause any tangible problem in real life... but better be on the safe side regarding thread safety). Luckily this is easy to fix.

Its other drawback is that as soon as the class Singleton is referenced, the singleton object is created, even if it is never actually used. This might be a problem if creation is costly. It can be avoided with the Initialization-on-demand Holder idiom.

like image 26
Péter Török Avatar answered Jan 20 '23 15:01

Péter Török