Search code examples
javamultithreadingconcurrencyhashmapsynchronization

Synchronize HashMap in multithreaded environment only for put and remove


I have two thread that shares a common HashMap, one thread will always insert an objects to the Map and the second thread will remove objects from the HashMap. my question is if this is the only logic of the two thread should I "protect" the Map with synchronize or ConcurrentHashMap, could I have a race condition? if yes can you please explain what is the risk of not protecting the Map.

thanks


Solution

  • could I have a race condition

    Yes, without synchronization or ConcurrentHashMap.

    It is clearly stated in the Javadoc of HashMap:

    Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

    You have two threads modifying the map structurally, so you need to synchronize if you use HashMap.

    please explain what is the risk of not protecting the Map

    Undefined behavior, ranging from doing completely the wrong thing (the very best kind of undefined behavior, because you know it needs fixing), down to seeming to work, until you change your JVM version and it mysteriously stops working (the very worst kind of undefined behavior).