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?

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?

Friday, December 29, 2006

Declaring Your Logger - No Problem

I used to like the java specialists newsletter, most news used to be a bit challenging. Nowadays however the quality is lower. In the latest news, the author proposes to use the StackTrace to get the class name, in order to declare a Logger independently of any explicit reference to the class name.

While this is a clever hack, it still requires some code to be duplicated in every class, compared to Aspect/IoC approach. But was there really a problem with declaring loggers the usual way in the first place?

With modern IDEs, most people just create a template for the logger declaration line. Also, renaming MyClass to MyClass2 will rename MyClass.class to MyClass2.class automatically. Here is my template for Eclipse to which I assigned the short name log4j:

private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);