A singleton pattern is probably the simplest well-known design pattern, but still people often implement it incorrectly in Java.
The main goal of the pattern is to ensure there is a single instance of a class accessible globally before it is first needed.
But wait, that could be accomplished just by a constant, right? Almost. But in reality, we often want to load the singleton lazily at the point we first need it, and we also want to ensure that it is not created multiple times in multi-threaded environments.
I’ve seen crazy complex solutions like this one to do it correctly. I mean, they are correct, but just too complex to implement by hand without a mistake. They are applicable in any language but they don’t take into account how JVM works to simplify the solution. (more…)