[英]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.假设我有一个名为 map 的共享 ConcurrentHashMap<String, Integer> 已经只有一个映射(“One”,1),并且还假设我有 2 个线程。
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.由于 ConcurrentHashMap 使用锁定条带方法而不是锁定整个 object 我不认为所描述的场景是线程安全的。 Particularly i don't know if there could be an interleaving of
map.put("One", 2);
特别是我不知道是否可能存在
map.put("One", 2);
的交错。 in first thread between Integer number = map.get("One");
在 Integer 之间的第一个线程
Integer number = map.get("One");
call and System.out.println(number == map.get("One"));
调用和
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. ConcurrentHashMap
中的所有方法都可能是线程安全的,但这并不意味着它在ConcurrentHashMap
object 本身上同步。 What you can do is synchronize put
and the map access code on the same reference.您可以做的是在同一参考上同步
put
和 map 访问代码。 Your put
code would have to be changed to this:您的
put
代码必须更改为:
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
.这将永远无法打印
false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.