Java Singelton fail

Exciting WTF moments at work (no joke, stuff I’ve seen coded by real Java professionals):

public static ThisObject getInstance(){
   return this.instance;
}

So far, so good. Looks like a normal singelton pattern.

public static void setInstance(ThisObject object){
    this.instance=object;
}

This seems to be a little odd. But ok, I’ve seen this before for smuggling Mock-Instances during jUnit-Test into the otherwise static-referenced Singleton. Not nice but quite applicable when Unit-Tests are created for code fragments using this singleton.

public static ThisObject createInstance(){
    return new ThisObject();
}

This code really caused some raising eyebrows. Turns out that someone reused some methods in a kind of stateless way, which where supposed to work only statefully within the instance of the singleton. So he created this little factory method which always created unused instances. This actually worked because no static fields were accessed within the methods.

public static void killInstance(){
    this.instance = null;
}

Code actually used with a lazyloading singleton pattern. Actually this was proven to be working code. Think about it. Twice.

Leave a Reply