A concurrent collection that maintains insertion order [closed]

冷暖自知 提交于 2019-12-14 01:19:23

问题


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

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

Thank you.


回答1:


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.

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.

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.




回答2:


A CopyOnWriteArrayList is a List that both maintains insertion order (as expected from a List) and allows concurrent access.

Docs here.




回答3:


Maximum will be 10k elements

If you have an extremely low update rate, CopyOnWriteArrayList is a possible solution. This will allow concurrent reads efficiently.

The problem you have is that concurrent and ordered are opposite concerns. To have ordering, you need to serialize updates to determine the order. To have concurrency you need to discard ordering.

There is a ConcurrentLinkedQueue, however this only allows concurrent read (1) and write (1)



来源:https://stackoverflow.com/questions/36724549/a-concurrent-collection-that-maintains-insertion-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!