Search code examples
javajava.util.concurrent

Creating a shallow copy of a concurrent collection in Java


I want to create a shallow copy of a concurrent collection, turning it into a regular collection. Is there a problem with doing it like this:

ledger = new ConcurrentLinkedDeque<>(); // this line is somewhere else in the program
//...
ArrayDeque<Operation> ledger_copy;
ledger_copy = new ArrayDeque<>(ledger);

The reason I ask is because while ledger is being used in the constructor of ArrayDeque it might be concurrently written to in other parts of the program.


Solution

  • It depends on what you consider "a problem". However, the usage of these collection classes is correct in the sense they are meant to be used.

    More specifically, the iterators exposed by ConcurrentLinkedDeque are weakly consistent:

    Iterators are weakly consistent, returning elements reflecting the state of the deque at some point at or since the creation of the iterator. They do not throw ConcurrentModificationException, and may proceed concurrently with other operations.

    Because of this, the elements in the ArrayDeque will also reflect the state of the ConcurrentLinkedDeque at some prior point in time.