[concurrency-interest] DCL clarification Immutable singelton

Vladimir Sitnikov 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
that creates
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
constructor),
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;
Singleton() {
  map = new HashMap();
  map.put("answer", 42);
}

Vladimir
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20140409/2ba306ad/attachment.html>


More information about the Concurrency-interest mailing list