[concurrency-interest] Initializing a map inside a constructor

Brian Goetz brian at quiotix.com
Mon Mar 5 14:00:54 EST 2007


This code is thread-safe:

public class Foo {
     private final Map m = new HashMap();

     public Foo() {
         m.put("foo", "bar");
     }

     public isKnown(String s) {
         return m.containsKey(s);
     }

     // no other modification to m
}

and this code is not:

public class Foo {
     private Map m = new HashMap();

     public Foo() {
         m.put("foo", "bar");
     }

     public isKnown(String s) {
         return m.containsKey(s);
     }

     // no other modification to m
}

The difference is the final keyword.  If the map is effectively 
immutable, and the reference to it is final, and the values are set in 
the constructor, and the 'this' reference doesn't escape construction, 
you're OK.

Howard Lewis Ship 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)?
> 


More information about the Concurrency-interest mailing list