Lazy Loading Singletons

Posted by Kerry Sun, 28 Jan 2007 11:40:00 GMT

Dejan Bosanac over at O’Reilly points out a style of initializing singletons which I hadn’t seen before.

I think there’s 3 things worth saying about this:

  1. Don’t use the Singleton pattern if you can avoid it. I should really dig up some references for this comment but I can’t be arsed.
  2. Use a static initializer if you can. It avoids having another class involved and I think it reads a bit easier.
  3. If you really need to have the Singleton inited on the getInstance call, then go ahead and use the on demand holder. In my experience the first call to a Singleton is the getInstance method so the static initialiser will be called at that stage anyway.