本文介绍了ConcurrentHashMap中的读操作关于返回值是否可靠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一本书中读到,读入 ConcurrentHashmap 并不保证最近更新的状态,它有时可以提供更接近的值。这是正确的吗?

I read in a book that read in ConcurrentHashmap does not guarantee the most recently updated state and it can sometimes gives the closer value. Is this correct?

我已经阅读了它的javadocs和许多博客似乎没有说明(即它是准确的)。

I have read its javadocs and many blogs which seems to say otherwise (i.e. it is accurate).

哪一个是真的?

推荐答案

直观地说,ConcurrentHashMap的行为应该像一组volatile变量;映射键是变量地址。 get(key) put(key,value)应该像volatile读写一样。

Intuitively, a ConcurrentHashMap should behave like a set of volatile variables; map keys being the variable addresses. get(key) and put(key, value) should behave like volatile read and write.

文件中没有明确说明。但是,我坚信这是事实。否则将会出现许多意外的,令人惊讶的行为,这些行为会破坏应用程序逻辑。
我不认为Doug Lea会对我们这样做。可以肯定的是,有人请在并发利息邮件列表中询问他。

That is not explicitly stated in the document. However, I would strongly believe that it is the case. Otherwise there will be a lot of unexpected, surprising behaviors that undermine application logic.I don't think Doug Lea would do that to us. To be sure, someone please ask him on concurrency-interest mailing list.

假设它确实遵守易失性语义,我们可以基于Java内存模型进行推理 -

Suppose it does obey the volatile semantics, we can reason based on Java Memory Model -

所有易失性读写都构成一个总订单。这可以被认为是伪时间线,其中读/写是其上的点。

All volatile reads and writes form a single total order. This can be considered a pseudo time line, where reads/writes are points on it.

易失性读取看到前一个易失性写入,并且只看到该写入。这里的前置是根据伪时间线。

A volatile read sees the immediate preceding volatile write, and sees only that write. "Preceding" here is according to the pseudo time line.

伪时间线可能与实际时间线不同。然而,理论上,不能在伪时间线上无限延迟易失性写入。并且,在实践中,两个时间线非常接近。

The pseudo time line can differ from "real" time line. However, in theory, a volatile write cannot be infinitely postponed on the pseudo time line. And, in pracitce, two time lines are pretty close.

因此,我们可以非常肯定,易读写应该非常快地读取。

Therefore, we can be pretty sure that, a volatile write should become visible "very quickly" to reads.

这篇关于ConcurrentHashMap中的读操作关于返回值是否可靠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:18