The Ironism

The Ironism


The lair of Lars J. Nilsson. Contains random musings on beer, writing and this thing we call life.

July 2007
MTWTFSS
« Jun Aug »
 1
2345678
9101112131415
16171819202122
23242526272829
3031 

Categories


Singletons… Again!

fungrimfungrim

Perhaps I’m being a bit grumpy today, but this article rubs me the wrong way. It describes the Singleton pattern in Java but contains some problems. And one of the is a pet peeve of mine. The article claims:

The singleton pattern does not guarantee anything regards to the number of instances of an object, and certainly not per JVM. You see, even if we disregard cloning, serialization, reflection or thread safety the following is still true: A class instance of an object is guaranteed to be unique per class loader, not JVM. In other words, if you have multiple class loaders (as do almost all application servers) you can have multiple instances of a singleton per JVM; one for each class loader.

Singletons can help guard limited resources such as object pooling. That is correct, but the implication that it is good design to use it to do so is wrong. Statically held object pools in larger and long running applications and servers are not a good idea as their lifetime cannot be directly controlled by the code. Also, if there are multiple class loaders… See the paragraph above.

And the synchronization discussion is naive as one of the comments suggests. See this, this, this or google it yourself.

So, yes, the Singleton pattern is useful, but not as massively so as many articles and tutorials suggests. In a world of serialization and class loader hierarchies it can be a real pain in the ass as well. Use with care.

The proprietor of this blog. Lunchtime poet, former opera singer, computer programmer. But not always in that order. Ask me again tomorrow.

    Comments 0
    There are currently no comments.