Enforce the singleton property with a private constructor or an enum type

A singleton is an object that is instantiated once and once only during runtime of an application. How can it be achieved? There are three common ways to do it: public static final field instance, static factory, enum.

What is the easiest way to implement a singleton? Have a public static final field instance and a private constructor, to guarantee that the class is not instantiated from outside. Easy and readable, since end user can explicitly see the field in the API.

public class Singleton {
    public static final Singleton INSTANCE = new Singleton();
    private Singleton() { throw new AssertionError(); }
}

A more flexible approach if your API might change sometime is a static factory method + private constructor. You can decide later if the getInstance() will return a singleton or a new instance. Here is the singleton example:

public class Singleton {
    private static Singleton INSTANCE = new Singleton();
    private Singleton() { throw new AssertionError(); }
    public Singleton getInstance() { return INSTANCE; }
}

In both cases, an exception thrown in the private constructor body, prevents its instantiation if somebody accesses it through reflection.

The most concise way to create a singleton is to use enum. Why should I use an enum as singleton implementation, you might ask? Well, it guarantees that there exists only one instance, without a need to guard yourself through the hidden constructor. It is also automatically serializable (the other two needs additional tuning). The drawback is that it cannot extend another non-enum class. Check enum singleton Java source code:

public enum Singleton {
    INSTANCE;
}

This post is based on item Enforce the singleton property with a private constructor or an enum type from Joshua Bloch Effective Java Third Edition (get it on Amazon: https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997)