i want to convert a ConcurrentHashMap to a TreeMap.Can i do that?
-
1I'm curious as to why. If this is for performance reasons (I might be out of date, but I believe there was at one time some performance overhead with the Concurrent collections), have you profiled to make sure that this is your bottleneck?– Thomas OwensCommented Aug 31, 2010 at 19:20
-
1You'll have to more specific. A ConcurrentHashMap is a threadsafe unordered map implementation. A TreeMap is a non-threadsafe ordered map implementation. Show a code snippet to illustrate what you mean by "convert".– Mike QCommented Aug 31, 2010 at 19:20
-
Please expand your question: Is this a one time conversion in order to access the contents in order one time, or a global code change to get sorted access multiple times?– DarronCommented Aug 31, 2010 at 19:43
3 Answers
If you need a Sorted ConcurrentMap look at ConcurrentSkipListMap. Considering its complexity it is both non blocking and fast. To be more specific:
This class implements a concurrent variant of SkipLists providing expected average log(n) time cost for the
containsKey, get, put and remove operations and their variants.
A ConcurrentHashMap
is still a Map
. So you can create a new TreeMap
like this:
ConcurrentHashMap myMap;
...
TreeMap myTreeMap = new TreeMap( myMap );
-
+1. Worth mentioning that the constructor runs in
n log(n)
time– Noel MCommented Aug 31, 2010 at 19:28
First I would like to point you. you should learn to read the java SDK documentation.
Like Tangens said, and the TreeMap API:
ConcurrentHashMAp myMap;
new TreeMap(myMap);
"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"
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));