is
final Map<Integer,Map<String,Integer>> status = new ConcurrentHashMap<Integer, Map<String,Integer>>();
Map<Integer,Map<String,Integer>> statusInner = new ConcurrentHashMap<Integer, Map<String,Integer>>();
status.put(key,statusInner);
the same as
volatile Map<Integer,Map<String,Integer>> status = new ConcurrentHashMap<Integer, Map<String,Integer>>();
Map<Integer,Map<String,Integer>> statusInner = new ConcurrentHashMap<Integer, Map<String,Integer>>();
status.put(key,statusInner);
in case the inner Map is accessed by different Threads?
or is even something like this required:
volatile Map<Integer,Map<String,Integer>> status = new ConcurrentHashMap<Integer, Map<String,Integer>>();
volatile Map<Integer,Map<String,Integer>> statusInner = new ConcurrentHashMap<Integer, Map<String,Integer>>();
status.put(key,statusInner);
In case the it is NOT a “cascaded” map, final and volatile have in the end the same effect of making shure that all threads see always the correct contents of the Map… But what happens if the Map iteself contains a map, as in the example… How do I make shure that the inner Map is correctly “Memory barriered”?
Tanks!
Tom
volatileonly affects the ability of other threads to read the value of the variables it’s attached to. It in no way affects the ability of another thread to see the keys and values of the map. For instance, I could have avolatile int[]. If I change the reference—i.e. if I change the actual array that it points to—other threads reading the array are guaranteed to see that change. However, if I change the third element of the array no such guarantees are made.If
statusisfinal, the construction of the containing class creates ahappens-beforerelationship with any subsequent reads, so they are able to see the value of status. Likewise any reads to yourvolatilevariable are guaranteed to see the latest reference assignment to it. It’s unlike you’re swapping the actual map around very often, more like you’re just changing keys and the overall map object stays as is.For this question, then, we need to consult the documentation for
ConcurrentHashMap:This is kind of oddly worded, but the gist is that any
getoperation whose onset is after someputoperation’s return is guaranteed to see the results of that put. So you don’t even need avolatileon the outer map; quoth the JLS:Summary
A
finalon the outer map is sufficient.