[concurrency-interest] Initializing a map inside a constructor

Thomas Hawtin tackline at tackline.plus.com
Mon Mar 5 15:08:15 EST 2007

Bob Lee wrote:
> On 3/5/07, *Howard Lewis Ship* <hlship at gmail.com 
> <mailto:hlship at gmail.com>> wrote:
>     I often have classes with a final field of type Map.
>     I initialize the Map, loading values inside the constructor.  I never
>     change the contents
>     of the Map outside of the constructor.

> You should be fine so long as you don't let the "this" reference escape 
> from the constructor (I assume this is the case), and if you create the 
> enclosing object in one thread and access it from another, you must pass 
> the object off in a thread safe manner.

My understanding is that you do not have to publish safely, as it is a 
final field. The canonical example is the char array in String.

Also a point of note that the JLS isn't very clear on is that it's the 
constructor of the class holding the field that is important, not the 
constructor of the leaf implementation class. You should be able to 
publish this from subclass constructors.

Of course it depends upon the (probably undocumented) implementation of 
the Map. HashMap you should be fine. Anything lazy, or dynamically 
optimising, or something like WeakHashMap, and you could be in trouble.

Tom Hawtin

More information about the Concurrency-interest mailing list