gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:50:10 24 4
gpt4 key购买 nike

我有一个关于 java 中的 ConcurrentHashMap 的问题。它在内部调用 readValueUnderLock。为什么在get操作的情况下需要锁定。在这种情况下,这个条件将为真 (条目.value==null)这会导致调用 readValueUnderLock)

最佳答案

来自readValueUnderLock的源码java文档注释

  /**
* 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.
*/

从这里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. (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. 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. In retrospect, I'm not so sure this was a good idea, since it leads people to come up with exotic theories.

关于java - 为什么 ConcurrentHashMap 中的 get 方法是阻塞的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12740844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com