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.
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.