Lazy Loading Singletons in Java (Initialization on Demand Holder (IODH) idiom)

Posted on Wednesday, March 14, 2012



Lazy Loading Singletons in Java

The other day I was reading a coding book and I saw an example of a lazy loaded singleton written in Java.  To my embarrassment I starred at it for far too long until I understood it.

In the past I have written out a lazy loading singleton in Java like this


    
public class MySingletonObject {

    private static MySingletonObject instance = null;

    private MySingletonObject {
    }

    public static MySingletonObject getInstance() {
        if(instance == null) {
            instance = new MySingletonObject();
        }
        return instance;
    }
}




Of course this is actually a bit of bad code it forgets about synchronizations.  Although it would be rare, the way this code is written it could cause more than one of this object to be created.

To fix this, it should be


    
public class MySingletonObject {

    private static MySingletonObject instance = null;

    private MySingletonObject {
    }

    public static syncrhonized MySingletonObject  
                                       getInstance() {
        if(instance == null) {
            instance = new MySingletonObject();
        }
        return instance;
    }
}



This works and loads lazily but it does have a big cost using a synchronized method.   

A better way to do it is to use the Initialization on Demand Holder (IODH) idiom, as shown in this code.

    
public class MySingletonObject {

    private MySingletonObject {
    }

    public static MySingletonObject getInstance() {
        return MySingletonObjectHolder.instance;
    }

    private static class MySingletonObjectHolder {
        static MySingletonObject instance = 
                              new MySingletonObject();
    }
}


I think one reason it took me a bit to understand this code is I saw the inner class as a method, when in fact it was an inner class.   I believe inner classes should be avoided in general.  I think this is a perfect example of when to use an inner class, but even so it does complicate the code and make it harder to read.

One funny thing is I went back to update some notes I made years ago on Java singletons, in which I wrote this exact class using the IODH idiom.  At the time it was new to me and I guess I did not grasp it as I should have.


References:

No comments:

Post a Comment