简体   繁体   中英

Can ConcurrentHashMap put() method be not thread-safe?

Suppose that i have a shared ConcurrentHashMap<String, Integer> called map that has already only one mapping ("One", 1), and suppose also that i have 2 threads.

The first thread executes this code:

map.put("One", 2);

and the second thread executes this code:

synchronized (map) {
    Integer number = map.get("One");
    System.out.println(number == map.get("One"));
}

Since ConcurrentHashMap works with lock striping method instead of locking entire object i don't think that the described scenario is thread safe. Particularly i don't know if there could be an interleaving of map.put("One", 2); in first thread between Integer number = map.get("One"); call and System.out.println(number == map.get("One")); call in second thread despite both are inside a synchronized block.

So is it possible that that code prints false?

All methods within ConcurrentHashMap might be thread-safe, but this does not mean that it synchronizes on the ConcurrentHashMap object itself. What you can do is synchronize put and the map access code on the same reference. Your put code would have to be changed to this:

synchronized (map) {
    map.put("One", 2);
}

And your access code can remain like:

synchronized (map) {
    Integer number = map.get("One");
    System.out.println(number == map.get("One"));
}

This will never be able to print false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM