简体   繁体   中英

How can I use a Java ConcurrentNavigableMap with comparator instead of a TreeMap?

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 .

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM