Smart thread safe implementation of the singleton pattern

Hi

I have just found this on Wikipedia:

[quote]public class Something {
private Something() {
}

    private static class LazyHolder {
            public static final Something INSTANCE = new Something();
    }

    public static Something getInstance() {
            return LazyHolder.INSTANCE;
    }

}
[/quote]
In which cases should we use an atomic reference instead of the example above?

The idea is if creating “Something” takes awhile to create, then to not bother until it is first used. I’m not sure why you’re comparing this to an atomic reference (but maybe my brain’s not working ATM), but it probably would make sense to create INSTANCE atomically in the given code example.

I don’t understand why he suggested a much complicated approach relying on atomic references:

He’s attempting to make it thread-safe without using a synchronized block.

He is after lazy initializing non-static fields in instances, not lazy initializing singletons. So basically over-engineered nonsense :wink:

But the example of Wikipedia already does it ???

Lol you reassure me. I felt stupid when I didn’t succeed in understanding what for he did that.

Just use a synchronized block. Actually you need two (aka “double checked locking”, and no it isn’t broken anymore). Better yet, stop inventing your own singleton pattern, which in that form is really nothing more than an antipattern, and use factory methods that enforce the “singleton-ness” in the factory and not in the class.

Are you sure it isn’t broken anymore?

Yes singleton is an antipattern but when I begin using a new API, I cannot immediately suggest design changes. I prefer using a factory in my own projects.

As sure as I am that there aren’t bugs in the implementation of the java memory model, yes, I’m quite sure. The JMM was created to address issues like the double-checked locking bug. The only thing “broken” about the idiom now is how slow it is, but that’s the price paid for safety (and it’s still faster than synchronizing on all accesses).

You mean double-checked locking using volatile booleans!?

No, not volatile booleans. One lock, two checks against null. Two locks if you count a synchronized setter, but volatile does the job for this idiom.


The second link is the pattern in the original post, but read all the way to “when not to use it” for one reason I don’t recommend it as a general pattern. The second is that I’m just not big on the GoF Singleton implementation in general.