[concurrency-interest] DCL clarification Immutable singelton
sitnikov.vladimir at gmail.com
Wed Apr 9 05:29:49 EDT 2014
>It's getting more
>problematic when Singleton contains values like HashMap or ArrayList; in
>that case it's not enough to declare them as final because the values
>themselves are not immutable. You'd had a safe publication of Singleton
>itself then, but not of its contents.
This is false.
It works fine if you create HashMap and its contents in the same thread
Singleton _and_ you do _not_ leak the created objects before assigning the
value to _instance.
If the map in question was created in a different thread or you somehow
publish the reference
before Singleton constructor completes (i.e. Globals.staticField = this; in
then crazy things can happen.
The order of initialization of the map and its contents does not matter.
For example, this is a safe publication of a map _and_ its contents.
However you'll have to synchronize mutations of the map if you need them.
final Map map;
map = new HashMap();
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Concurrency-interest