Wednesday 19 October 2016

Why to use ENUM for singleton

ENUM for singleton

If you have been writing Singletons prior to Java 5 than you know that even with double checked locking you can have more than one instances. Though that issue is fixed with Java memory model improvement and guarantee provided by volatile variables from Java 5 onwards but it still tricky to write for many beginners.

Enum on the otherhand is just a cakewalk

Enum are also classes. So enum instances are static class fields and so are initialized as part of class loading when you 1st access the class.
Classloading is synchronized internally so that ensures enum instances are singletons (singletons within the same classloader, that is. if you have the same enum loaded by multiple loaders you will get multiple instances).

So yes If the same enum gets loaded by more than one Classloader (when classloading games are being played by, for example, a web app container), you will have multiple incompatible instances in memory.

But the million dollar question is WHY will someone do like that ??

An Example of Enum vs Doubly Checked way of creating singleton.

Using Enum

public enum Singleton{
    instance;
    public void showMe(){
    }
}

Using Double Check Singleton

    public class DoubleCheckSingleton {

    private volatile DoubleCheckSingleton singletonInstance;

    private DoubleCheckSingleton() {
    }

    public DoubleCheckSingleton getInstance() {
        if (singletonInstance == null) {
            synchronized (DoubleCheckSingleton.class) { /*double checking */
                if (singletonInstance == null) {
                    singletonInstance = new DoubleCheckSingleton();
                }
            }
        }
        return singletonInstance;
    }

    public void showMe() {
    }
}

Usage

using Enum ->

Singleton.instance.showMe();

Using DoubleCheckSingleton Implementation.

DoubleCheckSingleton.getInstance().showMe();