3

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.

Xitrum
  • 7,765
  • 26
  • 90
  • 126

3 Answers3

4

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

Docs here.

Mena
  • 47,782
  • 11
  • 87
  • 106
3

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.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
0

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)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130