Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

java - 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?

question from:https://stackoverflow.com/questions/65848277/can-concurrenthashmap-put-method-be-not-thread-safe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...