我计划使用 CHM 实现一个简单的内存缓存来进行查找,该缓存最多由 2 个并发线程操作。第一个线程使用迭代器迭代和更新 CHM,第二个线程从 map 中读取值。
根据我的理解和到目前为止我所经历的 CHM 迭代器是故障安全的,这意味着迭代将发生在数据快照上。
因此,我们假设线程 A 从 CHM 中提取一个值,该值是使用键的 POJO,并且它正在迭代/更新 POJO。同时ThreadB 对同一个POJO 进行获取。那么此时预期的行为是什么?
- ThreadB 会看到 ThreadA 所做的更新吗?我想不是因为 ThreadA 仍在进行更新。
- 如果是,请分享您的想法,这将如何发生?
- 如果没有,请建议有效的替代方法(如果您已实现)。
POJO 如下所示。
Class Pojo{
private volatile long a;
private volatile long b;
....
public long getA() {
return this.a;
}
void setA(long a) {
this.a = a;
}
}
最佳答案
As my understanding goes and what I have experienced till now CHM Iterator is fail safe which would mean iteration would happen on a snapshot of data.
这是不正确的。每the documentation :
Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration.
[强调我的]
So let's assume Thread A extracts a value from CHM which is a POJO using a key and it is iterating/updating the POJO. At the same time ThreadB does a get on the same POJO. So what would be the expected behavior at this point?
如果线程 A 正在改变 POJO,而线程 B 正在检查相同的 POJO,则 ConcurrentHashMap 根本不相关:两个线程如何获取 POJO 并不重要,只是POJO 本身如何处理并发更新和读取。
您还没有告诉我们有关 POJO 类的任何信息,但除非它经过精心设计以允许原子更新和读取,否则或多或少线程 B 有时会以不一致的状态查看 POJO,其中线程 A 的一些读取,但不是全部。
关于java - 如何处理存储在 Map 中的 POJO 的并发更新和读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47171619/