[concurrency-interest] Initializing a map inside a constructor

Bob Lee crazybob at crazybob.org
Mon Mar 5 12:56:35 EST 2007


On 3/5/07, Howard Lewis Ship <hlship at gmail.com> wrote:
>
> I'm seeing some very strange effects in my code under load.  I've been
> reviewing Brian Goetz's concurrency book, but I have a scenario I
> frequently use that I have come to suspect:
>
> 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.
>
> I don't use a guard (i.e. synchronized) to access the map from other code.
>
> Is this thread safe, or do I need to synchronize the methods (or wrap
> the map in a synchronzing wrapper)?


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.

Bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20070305/71de452e/attachment.html 


More information about the Concurrency-interest mailing list