关于“ modCount”的“ HashMap”中的“ volatile”

时间:2019-06-14 02:35:11

标签: java hashmap

为什么HashMap不使用volatile来修改modCount以确保一个线程在另一个线程更改它时可以立即知道Map的更改?

以下代码段:

/**
 * The number of times this HashMap has been structurally modified
 * Structural modifications are those that change the number of mappings 
in
 * the HashMap or otherwise modify its internal structure (e.g.,
 * rehash).  This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 */
transient int modCount;

1 个答案:

答案 0 :(得分:4)

modCount声明为volatile的唯一好处是在某些情况下,可以使并发修改的“快速失败”检测更快……

  • 对于受线程限制的HashMap(即仅由一个线程使用),没有功能上的好处。保证该线程可以看到它对modCount所做的更新。

  • 对于不受线程限制但(以适当的方式)以其他方式同步的HashMap,同步应确保从另一个线程(而不是更新的线程)查看时,modCount不会过时它。再次,没有功能上的好处。

  • 对于没有线程约束且未正确同步的HashMap,您做错了,与“快速失败”相比,您要担心的大得多的问题 1 检测并发修改不是立即的。因此,好处是...。边际。

与上述说法相反的是,将modCount声明为volatile 会导致性能下降(以内存屏障和额外的内存读写形式)用于所有读取或写入该字段的HashMap操作。 (这就是大多数。)

总之:零收益或最低收益与性能开销在某些用例中可能非常重要。


1-例如heisenbug HashMap损坏。

相关问题