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.

Jon Skeet
people
quotationmark

Assuming you're doing all of this in multiple threads, no, it's not thread-safe.

Ignore the fact that you've accessed the TreeMap via a ConcurrentHashMap - you end up with multiple threads accessing the TreeMap at the same time, including one or more of them writing to the map. That's not safe, because TreeMap isn't thread-safe for that situation:

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

people

See more on this question at Stackoverflow