Search code examples
javahashmap

”volatile“ in the ”HashMap“ about ”modCount“


Why the HashMap don't use volatile to modify modCount to make sure that a thread can immediately know the change of the Map when another thread change it?

Snippet below:

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

Solution

  • The only benefit of declaring modCount to be volatile would be to make the "fail fast" detection of concurrent modifications faster ... in some cases:

    • For a HashMap that is thread confined (i.e. used by only one thread) there is no functional benefit. The thread is guaranteed to see the updates that it makes to modCount.

    • For a HashMap that is not thread confined but (properly) synchronized some other way, the synchronization should ensure that modCount is not stale when viewed from another thread than the one that updated it. Again, no functional benefit.

    • For a HashMap that is not thread confined and not properly synchronized, you are doing it wrong. You have much bigger problems1 to worry about than "fail fast" detection of concurrent modifications not being immediate. So the benefit is .... marginal.

    And the counterpoint to the above is that declaring modCount to be volatile will incur a performance penalty (in the form of memory barriers and extra memory reads and writes) for all HashMap operations that read or write that field. (And that is most of them.)

    In summary: zero or minimal benefit versus performance overheads that could be significant in some use-cases.


    1 - For example, heisenbug HashMap corruptions.