Reputation: 30895
I need build Queue that will stay allways sorted by its keys .
the TreeMap seams to be great for it like in this example :
http://www.javaexamples4u.com/2009/03/treemap-comparator.html
but the big problem is that its not thread safe , then i found ConcurrentNavigableMap
great , but how do i use the comparator the same way as with the TreeMap? i didn't found any example for it .
Upvotes: 0
Views: 1421
Reputation: 21795
ConcurrentNavigableMap is just the interface. You need to use a concrete class implementing it, which in the standard collections library is ConcurrentSkipListMap.
You should basically be able to use ConcurrentSkipListMap as a drop-in replacement for TreeMap, including using the comparator. Operations will generally have similar performance characteristics (O(log n)), but as I understand the size() operation of ConcurrentSkipListMap requires traversal of the skip list rather than simply reading a variable, so just be slightly careful if you call this frequently on a large map.
Upvotes: 1
Reputation: 33171
It sounds like you are actually looking for a PriorityQueue. If you need a thread-safe version of it, you can use a PriorityBlockingQueue.
A priority queue is a queue where you can retrieve items ordered by "importance." In the case of Java, you can use a Comparator or the items' natural order (if they implement Comparable).
If you really need to use a ConcurrentNavigableMap, you will need to use an implementation of it such as ConcurrentSkipListMap. Just allocate an instance of ConcurrentSkipListMap and pass it the comparator you want to use.
new ConcurrentSkipListMap<MyKeyType, MyValueType>(new MyKeyComparator());
Upvotes: 1