简体   繁体   English

为什么ConcurrentHashMap中的get方法是阻塞的?

[英]Why get method in ConcurrentHashMap is blocking?

I have a question on ConcurrentHashMap in java. 我在java中有一个关于ConcurrentHashMap的问题。 It internally calls readValueUnderLock. 它在内部调用readValueUnderLock。 Why locking is required in case of get operation. 为什么在获取操作时需要锁定。 And in which case this condition will be true (Entry.value==null) which cause readValueUnderLock to be called) 在这种情况下,这个条件将成立(Entry.value == null),这会导致调用readValueUnderLock)

From the source code java doc comment of readValueUnderLock 从源代码java doc注释readValueUnderLock

  /**
     * Reads value field of an entry under lock. Called if value
     * field ever appears to be null. This is possible only if a
     * compiler happens to reorder a HashEntry initialization with
     * its table assignment, which is legal under memory model
     * but is not known to ever occur.
     */

From this link 从这个链接

Not quite. 不完全的。 You are right that it should never be called. 你是对的,永远不应该被召唤。 However, the JLS/JMM can be read as not absolutely forbidding it from being called because of weaknesses in required ordering relationships among finals vs volatiles set in constructors (key is final, value is volatile), wrt the reads by threads using the entry objects. 但是,JLS / JMM可以被读作并非绝对禁止被调用,因为在构造函数中设置的终结符号与挥发性之间所需的排序关系存在弱点(键是最终的,值是易失性的),而线程使用条目对象进行读取。 (In JMM-ese, ordering constraints for finals fall outside of the synchronizes-with relation.) That's the issue the doc comment (pasted below) refers to. (在JMM-ese中,韵母的排序约束超出了同步关系。)这就是doc评论(粘贴在下面)引用的问题。 No one has ever thought of any practical loophole that a processor/compiler might find to produce a null value read, and it may be provable that none exist (and perhaps someday a JLS/JMM revision will fill in gaps to clarify this), but Bill Pugh once suggested we put this in anyway just for the sake of being conservatively pedantically correct. 没有人想到处理器/编译器可能会发现产生空值读取的任何实际漏洞,并且可能证明不存在(也许有一天JLS / JMM修订版将填补空白以澄清这一点),但是Bill Pugh曾经建议我们无论如何只是为了保守迂腐地纠正这个问题。 In retrospect, I'm not so sure this was a good idea, since it leads people to come up with exotic theories. 回想起来,我不太确定这是一个好主意,因为它引导人们提出异国情调的理论。

In order to read a value from a hash map the code must find the value first. 为了从哈希映射中读取值,代码必须首先找到该值。 If another thread adds a value while the first thread is finding the value it could derail the search. 如果另一个线程在第一个线程找到值时添加了值,则可能会使搜索脱轨。 Essentially the hash map could do something like: 基本上哈希映射可以做类似的事情:

calculate hash
go to location hash in the array
look to see if there's a list
iterate through the list until value is found

If this list is say an array list and the other thread needs to resize it, this would be a big problem for the thread iterating through it. 如果这个列表是一个数组列表而另一个线程需要调整它,那么对于迭代它的线程来说这将是一个大问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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