Hashmap in multithreaded environment when doing resizing

前端 未结 3 608
长情又很酷
长情又很酷 2021-01-31 23:42

I am following a tutorial and it basically explains about the cause of race condition which happens when resizing Hashmap in a multithreaded environment:

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 00:02

    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.

提交回复
热议问题