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);
...
}
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.
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.
The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
CopyOnWriteArrayList class – It is a thread-safe variant of ArrayList.
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();
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With