javamultithreadingthread-safetyhashmap

Is a HashMap thread-safe for different keys?


If I have two multiple threads accessing a HashMap, but guarantee that they'll never be accessing the same key at the same time, could that still lead to a race condition?


Solution

  • In @dotsid's answer he says this:

    If you change a HashMap in any way then your code is simply broken.

    He is correct. A HashMap is not thread-safe by design. If it is updated without proper synchronization it may break, even if the threads are using disjoint sets of keys1. Here are just some2 of the things that can go wrong.

    And if you have two threads simultaneously doing get requests and put or remove requests, there are numerous opportunities for race conditions at the application level as described in this answer.

    I can think of three solutions:


    1 - Even though the key sets are disjoint, keys from one set will at some point end up on the same hash chain as keys from another set. This is unavoidable.
    2 - We cannot enumerate all of the possible things that could go wrong. For a start, we can't predict how all JVMs will handle the unspecified aspects of the JMM ... on all platforms. But you should NOT be relying on that kind of information anyway. All you need to know is that it is fundamentally wrong to use a HashMap like this. An application that does this is broken ... even if you haven't observed the symptoms of the brokenness yet.