Search code examples
javacollectionsconcurrentmodification

A concurrent collection that maintains insertion order


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.


Solution

  • 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.