The question came up when I saw this code:
private static volatile ConcurrentHashMap<String, String> cMap = null;
static {
cMap = new ConcurrentHashMap<String, String>();
}
To me it looks like the volatile there is redundant as the container is ConcurrentHashMap which according the JavaDoc already has synchronized puts, DUH, the class that uses the cMap only instantiates it once and doesn’t have any methods of setting or getting it.
The only thing I see volatile providing here is that if I would be setting the cMap to reference a new object in near future, those reads and writes would be synchronized.
Am I missing something?
The
volatilemodifier doesn’t have anything to do with the class involved – it’s only to do with the variablecMap. It only affects how a thread fetches or changes the value of that variable. By the time you’ve got as far as invoking methods on the referenced object, you’ve gone beyond the bailiwick ofvolatile.As you say, it basically makes sure that all threads would be guaranteed to see changes to the
cMapvalue (i.e. making it refer to a different map).That may be a good idea – or it may not, depending on what the rest of the code does. If you could make it
finalfor example, you wouldn’t need it to bevolatile…