维护插入顺序的并发集合 [英] A concurrent collection that maintains insertion order

查看:66
本文介绍了维护插入顺序的并发集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找可以维持广告插入顺序的并发列表。有人推荐吗?

I'm looking for a concurrent list that can maintain the insertion order. Does anyone have some good recommendation ?

我从番石榴里看一些东西,例如SetFromMap,但在新版本中已弃用。

I look at some from guava e.g. SetFromMap, but they are deprecated in the new version.

谢谢。

推荐答案

如果大多数情况下是读操作,则写操作很少,并且没有太多元素,则可以使用 CopyOnWriteArrayList ,因为它是 List 的无锁实现,用于读取操作,因此它几乎不可能更快,但它对于写操作而言非常昂贵,因为每次写操作都需要重新构建整个列表,以便能够为其提供新的只读副本接下来的读取操作。

If you have mostly read operations, very few write operations and you don't have too much elements then you can use CopyOnWriteArrayList as it is a lock free implementation of a List for read operations such that it can hardly be faster but it is very costly for the write operations as for every single write, it re-builds the entire List to be able to provide a new read-only copy for the next read operations.

根据您的情况,您有很多写操作和很多元素要放入集合中, CopyOnWriteArrayList 显然不是您的选择。

As in your case, you have many write operations and a lot of elements to put in your collection, CopyOnWriteArrayList is clearly not an option for you.

在您的情况下,我建议使用一个线程安全的<您可以在 java.util.concurrent 包中找到code> Queue 。根据您的情况和您的JDK版本,最佳选择可能会发生变化,但是如果您特别不需要阻塞队列 deque ,但只有一个纯集合,最佳选择可能是 ArrayBlockingQueue ConcurrentLinkedQueue LinkedBlockingQueue ,但根据此基准测试结果(有点旧), LinkedBlockingQueue 提供了最佳的整体性能。

What I suggest in your case, is to use one thread-safe Queue that you can find into the java.util.concurrent package. According to your context and your JDK version the best choice may change, but if you don't specifically need a blocking queue or a deque but only a pure collection, the best choices are probably ArrayBlockingQueue, ConcurrentLinkedQueue or LinkedBlockingQueue but according to this benchmark result (a little bit old), the LinkedBlockingQueue provides the best overall performances.

但是,当我们谈论性能时,最重要的建议是:始终在目标环境上进行测试,这是唯一有效的方法知道什么是您的最佳选择。

But when we talk about performances, the first and most important advice is: always test on your target environment, it is the only valid way to know what is the best choice for you.

这篇关于维护插入顺序的并发集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆