[concurrency-interest] DCL clarification Immutable singelton

Michael Kuhlmann concurrency at kuli.org
Wed Apr 9 05:55:42 EDT 2014


Am 09.04.2014 11:29, schrieb Vladimir Sitnikov:
>>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.

My bad! You are right: As long as all fields of Singleton are final, the
publication is safe, independent of the mutability of their contents.

So forget what I wrote about HashMaps and ArrayLists.

Just one minor clarification:

It's of no matter whether _instance was assigned or not as long as
_instance if not volatile. You just mustn't leak the created objects
before the constructor execution is finished.

> 
> 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

Correct.

-Kuli


More information about the Concurrency-interest mailing list