[英]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
TreeMap接口很适合它,就像在这个例子中: http : //www.javaexamples4u.com/2009/03/treemap-comparator.html但是最大的问题是它不是线程安全的,然后我找到了ConcurrentNavigableMap
great , but how do i use the comparator the same way as with the TreeMap? 很好,但我如何使用比较与TreeMap相同的方式? i didn't found any example for it .
我没有找到任何例子。
ConcurrentNavigableMap is just the interface. ConcurrentNavigableMap就是这个界面。 You need to use a concrete class implementing it, which in the standard collections library is ConcurrentSkipListMap .
您需要使用实现它的具体类,它在标准集合库中是ConcurrentSkipListMap 。
You should basically be able to use ConcurrentSkipListMap as a drop-in replacement for TreeMap, including using the comparator. 您基本上应该能够使用ConcurrentSkipListMap作为TreeMap的替代品,包括使用比较器。 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.
操作通常具有类似的性能特征(O(log n)),但据我所知,ConcurrentSkipListMap的size()操作需要遍历跳过列表而不是简单地读取变量,所以如果你经常调用它,就要小心点一张大地图。
It sounds like you are actually looking for a PriorityQueue . 听起来你实际上在寻找PriorityQueue 。 If you need a thread-safe version of it, you can use a PriorityBlockingQueue .
如果您需要它的线程安全版本,则可以使用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).
对于Java,您可以使用Comparator或项目的自然顺序(如果它们实现Comparable)。
If you really need to use a ConcurrentNavigableMap, you will need to use an implementation of it such as ConcurrentSkipListMap . 如果确实需要使用ConcurrentNavigableMap,则需要使用它的实现,例如ConcurrentSkipListMap 。 Just allocate an instance of ConcurrentSkipListMap and pass it the comparator you want to use.
只需分配一个ConcurrentSkipListMap实例并将其传递给您想要使用的比较器。
new ConcurrentSkipListMap<MyKeyType, MyValueType>(new MyKeyComparator());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.