I am looking at this piece of code. This constructor delegates to the native method “System.arraycopy”
Is it Thread safe? And by that I mean can it ever throw a ConcurrentModificationException?
public Collection<Object> getConnections(Collection<Object> someCollection) {
return new ArrayList<Object>(someCollection);
}
Does it make any difference if the collection being copied is ThreadSafe eg a CopyOnWriteArrayList?
public Collection<Object> getConnections(CopyOnWriteArrayList<Object> someCollection) {
return new ArrayList<Object>(someCollection);
}
Edit:
I am aware that ThreadSafe != ConcurrentModificationException. I am trying to take a snapshot of data at a point in time. Therefore if another Thread writes to someCollection midway thru the copy I dont care if the result has the new object or not. I just dont want it to throw a ConcurrentModificationException or worse
Your question is whether you can safely get a snapshot of a collection that might be undergoing concurrent modification by another thread using
new ArrayList<Foo>(thatCollection). The answer is: as long asthatCollectionitself is thread-safe, yes. So if it’s aCopyOnWriteArrayList,synchronizedListorVector, If it’s not thread-safe, for example if it’s anotherArrayList, you’re not fine. (What will happen could be worse than aConcurrentModificationException.)The reason is that the
ArrayListconstructor makes only a single atomic call to the other collection — to itstoArraymethod. So it essentially enjoys whatever thread-safety guarantees that method itself has. It was not always implemented like this, but is now for just this reason. We do the same thing in Guava withImmutableList.copyOf.