Search code examples
javamultithreadinghashmapmemory-barriers

Mutating/Reading a HashMap from multiple threads but one thread at a time


I want to use a LinkedHashMap in a multi-threaded environment, where multiple threads can access the hashmap (read/write), but only one thread will do so at one time. Hence synchronization is not required. But, I need to ensure that the changes done by one thread are readable by any other thread which accesses it later. For example:



    LinkedHashMap map = new LinkedHashMap();
    // Thread 1 
    map.put(key1, val1);

    // Thread 2. It starts after thread 1 has finished.
    Object val = map.get(key1);
    assert(val == val1);

..edit

Some people wanted the question to be explicitly stated. So here it is:

"I want to ensure that the changes done to a LinkedHashMap are visible to other threads i.e the changes are written to the main memory, and other threads read the map from main memory only. There is no concurrent access of the map."


Solution

  • The answer depends on how exactly you enforce "only one thread will access the map at one time". (The naive understanding of time is inapplicable here. Synchronization is what gives the meaning to time in programs). If you are piggybacking on external synchronization anywhere else, then it's probably work, albeit in a fragile way.

    "I want to ensure that the changes done to a LinkedHashMap are visible to other threads i.e the changes are written to the main memory, and other threads read the map from main memory only."

    Then you have to use synchronization. Nothing else will get you the semantics you are asking for. Guarding all accesses with synchronized on the same object is a routine way, but that penalizes the reads. It might be more performant to guard the LinkedHashMap accesses with ReadWriteLock, if reads greatly outnumber the writes.