I am following a tutorial and it basically explains about the cause of race condition which happens when resizing Hashmap in a multithreaded environment:
Actually there is at least one race condition related to rehashing. Look at this code fragment (it is from Sun JDK7):
boolean oldAltHashing = this.useAltHashing;
this.useAltHashing |= sun.misc.VM.isBooted() && (this.newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
boolean rehash = oldAltHashing ^ this.useAltHashing;
transfer(newTable, rehash);
this.table = newTable;
Here It is possible that thread T1 ends up with rehash = true
and thread T2 ends up with rehash = false
(let's suppose T1 has already changed the value of this.useAltHashing
).
Now, guess that which thread will write the this.table
- you have no idea, either can. So, it's a question of luck whether you get a consistent internal state or not.
Anyway, as I mentioned in my comment by design, it is not supposed to use HashMap in a multithreaded environment. It will not work. Either because of this, or because of other reasons. The above was just one example why you shouldn't try to go against the contracts.