Simplify Your Singletons

Posted by & filed under , .

ScriptingI’ve seen recently some Java code (I’m not telling whose, you probably know who you are :p) where a singleton pattern was involved. Nothing unusual here, you would say — and you’re right, I probably found myself using Singleton and Factory and Observer in pretty much every single Java project I ever worked on. The only issue here is that the developer had an attempted on using the double-checked locking — and pretty much failed at it (sorry, had to be said!).

Now, I guess as a beginner is perfectly normal to make these sort of mistakes — and learn from them. So I wouldn’t read too much into this; however, looking at the code, it occurred to me that there are such handy libraries like Apache Commons Lang (and others) which are not so known to some of the dev’s out there, yet they contain some handy classes which can help with situations like this. So I set off to write this post to promote a simpler way of setting up your singletons — guaranteed it’s not the only one (“use enum’s” I hear you say), but nevertheless it is one way of doing it.

So stripping down all the synchronization, initialization etc, this is what your typical singleton class looks like:

 

/**
 * Skeleton for a singleton class.
 *
 * @author Liviu Tudor http://about.me/liviutudor
 */
public class Singleton {
    /** The one and only instance. */
    private static Singleton instance;
 
    /** Private constructor, taking forever :-) */
    private Singleton() {
        // really complex initialization here
    }
 
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

As I said, in the above example I’ve left out the whole synchronization inside getInstance() — this can be as simple as synchronizing on the class object itself, using a double-checked locking, a read-write lock etc. Each one of them has its pro’s and con’s and more to the point, each one has its headaches in terms of implementing it: whether you like it or not you will end up writing code around it! (And this code is simply meant to handle the multi-threading aspect of your singleton, rather than some business logic.)

I’m not disputing here that there are cases when indeed writing the synchronization code is needed — especially when you might want to notify other components upon creation and/or carry out some other actions — but if all you want is just a standard boiler-plate code to handle this so you can concentrate on the rest of your app, help is at hand by using Apache Commons Lang and LazyInitializer class (org.apache.commons.lang3.concurrent.LazyInitializer to be more precise).

This is a simple abstract class which requires you to implement just an initialize() function and handles the complicated aspect of get() for you. As such, you can re-write your singleton using such a LazyInitializer as follows:

/**
* Skeleton for a singleton class.
*
* @author Liviu Tudor http://about.me/liviutudor
*/
public class Singleton {
 /** The one and only instance. */
 private static LazyInitializer<Singleton> instance = new LazyInitializer<Singleton>() {
  @Override
  protected Singleton initialize() throws ConcurrentException {
   return new Singleton();
  }
 };
 
 /** Private constructor, taking forever :-) */
 private Singleton() {
  // really complex initialization here
 }
 
 public static Singleton getInstance() throws ConcurrentException {
  return instance.get();
 }
}

You can of course have variations of the code above. One would be to use an inner class rather than just an anonymous inner class — and if you do that you might want to drop the ConcurrentException as well if your initialization is not prone to exceptions (hmmmm unlikely though, right?).

Or another variation of it would be to actually have your Singleton class extend LazyInitializer straight away — and reduce the code complexity even more:

/**
* Skeleton for a singleton class.
*
* @author Liviu Tudor http://about.me/liviutudor
*/
public class Singleton extends LazyInitializer<Singleton> {
 @Override
 protected Singleton initialize() throws ConcurrentException {
  return new Singleton();
 }
 
 /** Private constructor, taking forever :-) */
 private Singleton() {
  // really complex initialization here
 }
}

You can also add more code in the initialize() method — such that apart from object creation you might want to send some notifications around, log some stuff etc.

Nevertheless, the point of this exercise is that you don’t write the singleton code anymore and simply concentrate on writing your constructor (initialization) code and offload the whole synchronization to the LazyInitializer class and save yourself some headaches and time!

 

Leave a Reply

Your email address will not be published.