Is volatile redundant in this code?
public class Test {
private volatile Map<String, String> map = null;
public void resetMap() { map = new ConcurrentHashMap<>(); }
public Map<String, String> getMap() { return map; }
}
In other words, does map = new ConcurrentHashMap<>(); provide any visibility guarantees?
As far as I can see, the only guarantee provided by ConcurrentMap is:
Actions in a thread prior to placing an object into a ConcurrentMap as a key or value happen-before actions subsequent to the access or removal of that object from the ConcurrentMap in another thread.
How about other thread safe collections in java.util.concurrent (CopyOnWriteArrayList, etc.)?
volatileis not redundant as you are changing the reference to the map. i.e. ConcurrentMap only provides guarentees about the contents of the collection, not references to it.An alternative would be
Only the behaviour of the collection is thread safe. Reference to the collection are not thread safe, elements in the collection are not made thread safe by adding them to the collection.