Thursday, January 04, 2007

Tired Of Bad Singletons

While looking through some code for a project, I saw that:

  public static final ProductYP instance = new ProductYP();
 
  public ProductYP()
  {
    if (instance != null)
      throw new RuntimeException("Only one instance allowed");

    prods = new HashMap();
  }

  public static ProductYP getInstance()
  {
    return instance;
  }

And I don't think it was done by a newbie... It's actually not far from being correct, it's just that the guy obviously does not know about private constructors. I have seen several broken singleton implementations in previous projects and had several debates on the double-checked locking pattern (it works since JDK1.5 with volatiles but is useless). I am upset to see another half broken implementation. Everybody should have read at least this.

What have you seen as broken singletons?

4 comments :

  1. It drives me nuts to see singletons with a static instance, but then proceed to have all static fields and methods anyway.

    ReplyDelete
  2. john, you are devine. In the same class, that is what I have, a bunch of static methods. There is only one non static method...

    ReplyDelete
  3. I try to avoid singletons completely these days. They are difficult to "containerize" and most code ends up in some container or another. In fact the only place I can think of for them is in standalone GUI apps...

    ReplyDelete
  4. Singletons are just a fancy version of global variables, and should be avoided anyway.

    http://www.adrianmccarthy.com/blog/?p=53

    ReplyDelete