I’ve been interviewing a bunch of candidates lately ( we are hiring ) for a senior java developer’s position, and i’ve come to realize how far from the basics numerous people have become.  You ask them about some ajax feature, or new app on facebook, etc, they jump at the chance to talk about this, talk about that.  Ask them about some basic concepts, and other than textbook definitions, they can’t explain it.

The source of frustration for this post, is from an interview i had a couple weeks ago.  I asked the developer, who had about 2 years experience if i recall correctly and a bachelor’s degree in computer science ( i don’t recall from where, unfortunately), to explain to me what a singleton was.  His reply was typical, if not rehearsed

A singleton is an object that has only one instance in a virtual machine.  This is achieved by having a private constructor, and a static method that either returns an existing instance, or creates then returns the instance.

I love the singleton question, because it allows me to focus in on anything based on their answer.  I can follow up with threading, locking, resource allocation (database pools, etc ), memory allocation ( when is the instance created, etc ).  It is what i like to refer to as a ramp up question.  On the surface, its extremely easy to answer, but if the person don’t pay attention, or doesn’t know when to stop talking, they can get into real trouble.

On the surface the candidates answer was correct and accurate.  I decided to follow up with a how would you write such a method, the reply

I wouldn’t, i would put the @Scope(“singleton”) annotation or put singleton in the spring xml configuration

Once i climbed back into my chair, as i obviously fell out of it hearing that, i asked, what if you weren’t using spring, write me the code for it.  The candidate, wrote the code, but couldnt’ explain the threading risks, or the double checked locking failure .  So enough about interviews, here is the definitive method for implementing a singleton in java.

I did not invent this method, it is from Joshua Block’s Effective Java Reloaded talk from Google IO in 2008 at 28:56

public enum Elvis {
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {

The reason behind this, is that the enum is created when the class is loaded.  It is automatically serializable, and will always reload to the same instance. That’s all for now.