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 TreeMap
s this CHM holding, are they also thread safe inside CHM ?
The operations I am doing are:
get(K)
.tailMap(K,boolean)
method.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.
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.
See more on this question at Stackoverflow