Friday 13 February 2009

Implementation of the Singleton pattern

The last successful job interview that I had included a minor practical pen and paper exercise - "Show me how you would implement a Singleton in Java".

I'd been using the Singleton pattern for about 6 years by this stage, so I just jotted down the most basic implementation that I knew, something along the lines of:


public class Singleton
{
private static Singleton instance = new Singleton();

private Singleton()
{
}


public static Singleton getInstance()
{
return instance;
}
}


As I was doing this I thought of all the fancy examples I had seen in various projects that I have worked on and code snippets from various books that I had been reading at the time. So I did my typical self-deprecating thing of saying out loud, "I should probably have some lazy instantiation happening in the getInstance, but that could just be premature optimization".

That lead into a discussion with the interviewer who congratulated me on being one of the few candidates who had actually produced a truly threadsafe implementation. If I had delayed the instantiation until the getInstance was called, then I would have had to introduce some synchronization to prevent the possibility of the instantation happening multiple times, something along the lines of:


public final class Singleton
{
private static Singleton instance;

private Singleton()
{
}


/**
* synchronized to prevent multiple instantiations of Singleton
*/
public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();

return instance;
}
}


Then the overhead of the synchronization would have been introduced for each and every call to getInstance - not ideal.

Head First Design Patterns gives a good overview of a slightly better approach involving double-checked locking that I have added to my repertoire (suitable for JVMs 5 and upwards).

No comments:

Post a Comment