Singletons & Double Checked Locking

I regard singletons as being perhaps the dirtiest of the GoF patterns. It’s problematic to assume there would only ever need to be one of something. As an example – the project I am currently working on has a client side application which has a series of singletons that facade server functionality. It turns out that this works very well, except there’s no way to renew these singletons if the user wants to log out of the server and log in again with a different user account. This means currently, the application has to be closed and reopened. This isn’t a show-stopper, but it is annoying.

Regardless of this, implementing thread safe, lazy initialized singletons in Java has always been problematic due some problems with the Java Memory Model. This is covered in detail in this excellent developerWorks article. I was mistakenly under the impression that this had been fixed in Java 5, but alas – it appears not. What I wasn’t aware of until today is that there is an alternative thread safe manner in which to implement a lazy-initialising singleton:
Initialize on demand holder classes.

I think the better approach nowadays however is to wire your application together using the Spring framework. Spring is very lightweight to implement, and will take care of initializing your singleton-like objects in order and wiring them together. Since spring offers full object life-cycle support, it’s easy to have it close all your objects out, and re-initialise with new ones, should you desire that.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s