Som Som -4 years ago 93
Java Question

How to write a Singleton in proper manner?

Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as

public class Singleton {

private static Singleton ref;

private Singleton() {
}

public static Singleton getInstance() {
if (ref == null) {
ref = new Singleton();
}
return ref;
}
}


suddenly he told me this is old way of writing the class. Can any one please help me why he told like that.

Answer Source

The first thing which comes to my mind when creating a singleton is enum. I generally use enum to implement singleton:

enum Singleton {
    INSTANCE;
}

One benefit you get with using enum is with Serialization.

With singleton class, you would have to make sure that serialization and deserialization doesn't create a new instance by implementing the readResolve() method, while this is not the case with enum.

Using class you should create the singleton like this:

public final class Singleton implements Serializable {
    // For lazy-laoding (if only you want)
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    private Singleton() {
        if (SingletonHolder.INSTANCE != null) {
            // throw Some Exception
        }
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    // To avoid deserialization create new instance
    @SuppressWarnings("unused")
    private Singleton readResolve() {
        return SingletonHolder.INSTANCE;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download