Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList(Collection<? extends E> c) thread safe?

Is it thread safe to create a new instance of ArrayList via constructor ArrayList(Collection<? extends E> sourceCollection) without any additional sychronization, supposing that sourceCollection is synchronized? More specifically, can we rely in that case on the new list to contain exactly the elements that were in the collection at the time new ArrayList(sourceCollection) was invoked? And can we rely on the new list to be in a consistent state?

I'm asking this question because I've seen examples in books on concurrency of how to confine objects to local variables on a thread's stack. In these examples a method is passed a reference to a shared object, and inside the method a copy of the object is stored in a local variable -- all this without any synchronization. It is claimed that thread safety can be achieved in this way. A general example would be:

public void someMethod(Collection<String> source) {
    List<String> localList = new ArrayList<>(source);
    ...
}
like image 794
Daniel Rusev Avatar asked Feb 14 '17 21:02

Daniel Rusev


People also ask

Is ArrayList thread-safe or not?

Vectors are synchronized. Any method that touches the Vector 's contents is thread safe. ArrayList , on the other hand, is unsynchronized, making them, therefore, not thread safe.

How do you make an ArrayList thread-safe?

A thread-safe variant of ArrayList in which all mutative operations (e.g., add, set, remove..) are implemented by creating a separate copy of an underlying array. It achieves thread safety by creating a separate copy of the List which is different than vector or other collections used to provide thread-safety.

Which collection classes are thread-safe?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

Which of the following is thread-safe version of ArrayList class?

CopyOnWriteArrayList class – It is a thread-safe variant of ArrayList.


1 Answers

Hint: as @John Bollinger justly mentioned, particular ArrayList implementation is not covered by language specification. So written below is true for Oracle java 8 implementation.


Yes, it is safe if source is synchronised collection, because ArrayList constructor in this case uses toArray() method of source collection, which is synchronised as well and produce new copy of data:

public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    // ...
}
like image 54
Andremoniy Avatar answered Oct 21 '22 15:10

Andremoniy