stonar96
stonar96

Reputation: 1461

Java ConcurrentLinkedQueue instead of List?

I have a worker thread which should iterate over an ArrayList<ConcurrentLinkedQueue>. Other threads can add and remove objects (queues). But ArrayList is not thread-safe. Would it be fine to use ConcurrentLinkedQueue<ConcurrentLinkedQueue> instead of ArrayList<ConcurrentLinkedQueue>?

Upvotes: 0

Views: 2169

Answers (1)

Stephen C
Stephen C

Reputation: 719229

If you are asking if you can iterate a ConcurrentLinkedQueue safely, then the answer is Yes. The javadoc says:

Iterators are weakly consistent, returning elements reflecting the state of the queue at some point at or since the creation of the iterator. They do not throw ConcurrentModificationException, and may proceed concurrently with other operations. Elements contained in the queue since the creation of the iterator will be returned exactly once.

However, there are things that you can do on a List that you cannot do on a Queue (e.g. positional get / set, insertion / removal of arbitrary elements.) If your application needs to do those things or similar, then using ConcurrentLinkedQueue instead of ArrayList won't work.

Also, beware that ConcurrentLinkedQueue.size() is an O(N) operation!

Upvotes: 2

Related Questions