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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…