Search code examples
javamultithreadingconcurrenthashmap

Using a thread safe static mutable Map of Map in Java


I need to add a static thread safe HashMap. I have something like this -

private static Map<String, ConcurrentHashMap<Integer, ClassA>> myCache =
      new ConcurrentHashMap<String, ConcurrentHashMap<Integer, ClassA>>();

Even though I am using ConcurrentHashMap, I see that if main thread is adding element in the myCache, and when the same is accessed in other thread even at later time, it does not have the latest data in the myCache object. For e.g

Thread 1: Adds entry to the map myCache = {a1={1=com.x.y.z.ClassA@3ec8b657}}

Thread 2: Access the same key a1. But it does not see the data added by Thread 1. Rather it sees empty value for this key myCache = {a1={}} As a result, data is getting corrupted. Entries added for the a1 key in Thread 1 are not visible in Thread 2.

Thanks in advance for any pointers on how can I update this map in thread safe manner.


Solution

  • The @Ryan answer is essentially correct.

    Remember that you must proxy every Map method that you wish to use and you must synchronize to the cashe element within every proxied method.

    For example:

    public void clear()
    {
      synchronized(cache)
      {
        cache.clear();
      }
    }