0

All, I was trying to understand the multiple thread race condition issue for the Hashmap resize function.

As I read from here. The race condition issue will cause the infinite loop link for the entry list.

I already knew that Hashmap has the fail-fast mechanism to immediately stop the multiple threads access it. The following code shows that.

if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

My question is why fail-fast doesn't work for the resize function? The code I debug is below.(jdk1.7)

void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

Because for doesn't use the Iterator?

Updated

Or Because resize function doesn't use the Put*, Remove*, Clear* method which will cause the modCount value changed? Please help to confirm it.(Forgive me the bad English.)

Thanks.

Joe.wang
  • 11,537
  • 25
  • 103
  • 180

1 Answers1

0

The Javadoc of HashMap explains it: ConcurrentModificationException is a best effort to detect a common programming bug (modifying while iterating).


 * Note that the fail-fast behavior of an iterator cannot be guaranteed
 * as it is, generally speaking, impossible to make any hard guarantees in the
 * presence of unsynchronized concurrent modification.  Fail-fast iterators
 * throw ConcurrentModificationException on a best-effort basis.
 * Therefore, it would be wrong to write a program that depended on this
 * exception for its correctness: the fail-fast behavior of iterators
 * should be used only to detect bugs.

Thus

fail-fast to immediately stop the multiple thread

is not guaranteed. And any unsynchronized concurrent modification may cause an undefined state.

Markus Kull
  • 1,471
  • 13
  • 16
  • This is from the link the OP posted "When two or more threads see the need for resizing the same hashmap, they **might** end up adding the elements of old bucket to the new bucket simultaneously and hence might lead to infinite loops. FYI, in case of collision, i.e, when there are different keys with same hashcode, internally we use single linked list to store the elements." So essentially, this statement can be extended from your answer. Am i correct? – Debosmit Ray Mar 02 '16 at 12:49