Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy ArrayList<T> in java multi-threaded environment?

In thread A, an ArrayList is created. It is managed from thread A only. In thread B, I want to copy that to a new instance.

The requirement is that copyList should not fail and should return a consistent version of the list (= existed at some time at least during the copying process).

My approach is this:

public static <T> ArrayList<T> copyList(ArrayList<? extends T> list) {
    List<? extends T> unmodifiableList = Collections.unmodifiableList(list);
    return new ArrayList<T>(unmodifiableList);
}

Q1: Does that satisfy the requirements?

Q2: How can I do the same without Collections.unmodifiableList with proably iterators and try-catch blocks?

UPD. That is an interview question I was asked a year ago. I understand this a bad idea to use non-thread-safe collections like ArrayList in multithreaded environment

like image 654
Ilya Smagin Avatar asked Dec 08 '22 22:12

Ilya Smagin


2 Answers

No. ArrayList is not thread safe and you are not using an explicit synchronization.

While you are executing the method unmodifiableList the first thread can modify the original list and you will have a not valid unmodifiable list.

The simplest way I think is the following:

  • Replace the List with a synchronized version of it.
  • On the copy list synchronize on the arrayList and make a copy

For example, something like:

List<T> l = Collections.synchronizedList(new ArrayList<T>());

...

public static <T> List<T> copyList(List<? extends T> list) {
    List<T> copyList = null;
    synchronized(list) {
        copyList = new ArrayList<T>(list);
    }
    return copyList;
}
like image 97
Davide Lorenzo MARINO Avatar answered Feb 16 '23 00:02

Davide Lorenzo MARINO


You should synchronize access to the ArrayList, or replace ArrayList with a concurrent collection like CopyOnWriteArrayList. Without doing that you might end up with a copy that is inconsistent.

like image 37
Krzysztof Krasoń Avatar answered Feb 16 '23 00:02

Krzysztof Krasoń