Thursday, August 12, 2010

Singleton for dummies

While searching for some coding practices, I realized some people are wondering how to do a singleton in Java (I know, this is considered an anti-pattern when badly used) :

public class Controller {

private static final Controller ctrl;

static {
ctrl = new Controller();

private Controller() {


public static Controller get() {
return ctrl;


That's the _only_ way to do it correctly in Java. Your static block is protected by the classloader lock, so everything is fine. This implementation _can_ bug, but that supposes you know how to subclass/implement a ClassLoader. In a webapp it's fine if you're wondering (well tomcat will leak your singleton memory if you abuse hot deploy).

I made this post as I'm reviewing some opush contributed code. What you can find on the net about java & singleton is quite fun. Nice article by someone who didn't know what are static blocks. Static blocks are "Java approved" since 2000.

No comments: