

Safe Publication and Safe Initialization in Java - Banzai
http://shipilev.net/blog/2014/safe-public-construction/

======
wink
I thought the best way to use singletons in Java these days was via enums,
e.g. as
[http://codereview.stackexchange.com/a/27298](http://codereview.stackexchange.com/a/27298)
describes it - can anyone elaborate on why that's not even mentioned in the
article?

~~~
jrochkind1
I _think_ that implementation is non-lazy? The OP is not interested in that
case.

> 3\. It is lazy. One can argue about this, but non-lazy factories are not
> interesting for our discussion. Singleton initialization should happen with
> the first request for a Singleton, not when Singleton class is initialized.
> If no one wants a Singleton instance, we should not instantiate it.

------
nobullet
I wonder why does Safe Local DCL (one volatile read when instance is present)
seem slower than Safe DCL (2 volatile reads when instance is present) in Table
4 (x86, 8 threads test)?

~~~
gresrun
Not sure, but their margins of error overlap so it could be just a blip. I
wouldn't read too much into those numbers; my take away is I always preferred
Safe DCL but Holder looks more performant and cleaner to write (at the cost of
an inner class).

I wish Java had a one-true-way for one-time static initialization like
dispatch_once() in Objective-C.

~~~
nobullet
You are right: it would be great to have one good approach. By the way, holder
solves the problem when you don't need to pass arguments to singleton
instance. In other cases Safe DCL, Safe Local DCL or Synchronized CL will
work.

