如何使用带有比较器的 Java ConcurrentNavigableMap 而不是 TreeMap?
我需要构建始终按其键排序的队列。 TreeMap 非常适合它,如下例所示: http://www.javaexamples4u.com/2009/03/treemap-comparator.html 但最大的问题是它不是线程安全的,然后我发现了 ConcurrentNavigableMap
太棒了,但是我如何像使用 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 .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您实际上正在寻找 PriorityQueue< /a>.如果您需要它的线程安全版本,可以使用 PriorityBlockingQueue。
优先级队列是一个可以检索按“重要性”排序的项目的队列。对于 Java,您可以使用比较器或项目的自然顺序(如果它们实现 Comparable)。
如果您确实需要使用 ConcurrentNavigableMap,则需要使用它的实现,例如 ConcurrentSkipListMap。只需分配一个 ConcurrentSkipListMap 实例并将其传递给您要使用的比较器即可。
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.
ConcurrentNavigableMap 只是接口。您需要使用一个具体的类来实现它,在标准集合库中是ConcurrentSkipListMap。
您基本上应该能够使用 ConcurrentSkipListMap 作为 TreeMap 的直接替代品,包括使用比较器。操作通常具有类似的性能特征(O(log n)),但据我了解 ConcurrentSkipListMap 的 size() 操作需要遍历跳过列表而不是简单地读取变量,因此如果您经常调用此操作,请稍微小心一张大地图。
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.