Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe publication of java.util.concurrent collections

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.)?

like image 229
assylias Avatar asked Aug 29 '12 11:08

assylias


1 Answers

volatile is 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

public class Test {
    private final Map<String, String> map = new ConcurrentHashMap<>();

    public void resetMap() { map.clear(); }

    public Map<String, String> getMap() { return map; }
}

How about other thread safe collections in java.util.concurrent (CopyOnWriteArrayList, etc.)?

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.

like image 102
Peter Lawrey Avatar answered Oct 16 '22 07:10

Peter Lawrey