Search code examples
javaconcurrencythread-safetytreemapconcurrenthashmap

is Treemap inside ConcurrentHashMap thread safe?


I have a case of nested maps as follows:

private final static Map<String, TreeMap<Long,String>> outerConcurrentMap = new ConcurrentHashMap<>();

I know that ConcurrentHashMap is thread safe, but I want to know about the TreeMaps this CHM holding, are they also thread safe inside CHM ?

The operations I am doing are:

  1. If specific key is not found --> create new TreeMap and put against key.
  2. If key is found then get the TreeMap, and update it.
  3. Retrieve TreeMap from CHM using get(K).
  4. Retreive data from TreeMap using tailMap(K,boolean) method.
  5. clear() the CHM.

I want a thread-safe structure in this scenario. Is the above implementation thread-safe or not? If not then please suggest a solution.


Solution

  • Once you've done TreeMap<?, ?> tm = chm.get(key); you are not in thread safe territory any longer. In particular, if another thread updates the treemap (through the CHM or not) you may or may not see the change. Worse, the copy of the map that you have in tm may be corrupted...

    One option would be to use a thread safe map, such as a ConcurrentSkipListMap.