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?

comments powered by Disqus
Tweet Submit to reddit
© 2006-16 Fabien Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License.