Singletons: Bill Pugh Solution or Enum

2017 October 9 @ 08:25pm by erik


In this blog post, Harinath Kuntamukkala discusses different approaches to the Singleton pattern. The first implementation he goes over is the Bill Pugh Solution, which is similar to the implementation we learned in class except it uses a static inner helper class as in the example below:

public class Logger {
    private Logger() {
        // private constructor
    }
    // static inner class - inner classes are not loaded until they are
    // referenced.
    private static class LoggerHolder {
        private static Logger logger = new Logger();
    }
    // global access point
    public static Logger getInstance() {
        return LoggerHolder.logger;
    }
    //Other methods
}

This would be the best approach, but it’s possible for more than one instance to be created with the use of Java reflection. For example:

public class LoggerReflection {
    public static void main(String[] args) {
        Logger instance1 = Logger.getInstance();
        Logger instance2 = null;
        try {
            Constructor[] cstr = Logger.class.getDeclaredConstructors();
            for (Constructor constructor: cstr) {
                //Setting constructor accessible
                constructor.setAccessible(true);
                instance2
                    = (Logger) constructor.newInstance();
                break;
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }

The solution to the problem suggested by Joshua Bloch, is to use Enum. The reason we use Enum is because Java ensures that any Enum value is instantiated only once. Using Enum, this is what the Logger class would look like


public enum Logger {
    INSTANCE;
    //other methods
}

It’s still possible for more than once instance to be created if a singleton object is serialized, then deserialized more than once. In order to avoid this you can implement a readResolve() method in the Logger Singleton class:


public class Logger implements Serializable {
    //other code related to Singleton
    //call this method immediately after De-serialization
    //it returns an instance of singleton
    protected Object readResolve() {
        return getInstance();
    }
}

The reason I chose this resource is because we are currently learning about design patterns and just reviewed the singleton pattern. This post goes into the best implementations of the singleton pattern and why that is, I would like to stay up to date on the most effective, clean and efficient implementations of design patterns. I think this is a useful post, and learned about the Bill Pugh Solution and the Enum solution to ensure there’s only one instance of a singleton object. The author concluded that the Enum approach is the best solution as it 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 instantiations, even in the face of sophisticated serialization or reflection attacks.”

I expect to take what I learned in this article and use it whenever implementing the singleton design pattern, and I might rework the code I have now to make use of the Enum approach talked about in the article.

0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

 

by erik christensen - powered by wordpress