There are many ways to implement the Singleton pattern in Java, but none of them is as clean, compact and close to fool-proof as using an ``++enum++``. Without an ``++enum++``, the implementer must take care to properly handle thread-safety, serialization, and classloaders, but those things come for free with an ``++enum++``. 


== Noncompliant Code Example

----
public class Highlander implements Serializable { // Serializable makes Singleton tricky to get right
  private static final Highlander INSTANCE;

  public static synchronized Highlander getInstance() {
    if(INSTANCE == null) {
      INSTANCE = new Highlander();
    }
    return INSTANCE;
  }

  private Highlander () {}

  private final String [] rivals = {"The Kurgan", "Ramirez"}; // oops, not serializable now

  private Object readResolve() { 
    return INSTANCE;
  }

  ...
}
----


== Compliant Solution

----
public enum Highlander {
  INSTANCE;

  private final String [] rivals = {"The Kurgan", "Ramirez"};

  ...
}
----


== See

* https://wiki.sei.cmu.edu/confluence/x/_zZGBQ[CERT MSC07-J.] - Prevent multiple instantiations of singleton objects

