Alex Rivera | Logout

Concurrent Reads from Unmodfiable Map

Asked 2011-04-22T13:00:49.400
10

If I statically initialize a map and set the reference to a Collections.unmodifiableMap(Map m). Do I need to synchronize reads?

private static final Map<String,String> staticMap; 
static{
   Map<String,String> tempMap = new HashMap<String,String>();

   tempMap.put("key 1","value 1");
   tempMap.put("key 2","value 2");
   tempMap.put("key 3","value 3");

   staticMap = Collections.unmodifiableMap(tempMap);
}
Edit
Report

1 Answer

10

No, the map you're creating there is effectively immutable (since nothing has a reference to the mutable backing map) and safe for concurrent access. If you want a clearer guarantee of that along with making it easier to create the map, Guava's ImmutableMap type is designed for just this sort of use (among other things):

private static final ImmutableMap<String, String> staticMap = ImmutableMap.of(
    "key1", "value1",
    "key2", "value2",
    "key3", "value3");
answered 2011-04-22T13:13:43.807

Your Answer