In case of CopyOnWriteArrayList
, a new object is created whenever an element is added into the collection.
Consider below example:
private static void copyOnWriteArrayList() {
List<String> playersUsing2 = new CopyOnWriteArrayList<String>();
System.out.println("Original hashCode = " + playersUsing2.hashCode());
playersUsing2.add("a1");
System.out.println("After a1 hashCode = " + playersUsing2.hashCode() + " size = " + playersUsing2.size());
addElement(playersUsing2, "a2");
System.out.println("After b1 from copyOnWriteArrayList hashCode = " + playersUsing2.hashCode() + " size = " + playersUsing2.size());
playersUsing2.add("b1");
System.out.println("After b1 hashCode = " + playersUsing2.hashCode() + " size = " + playersUsing2.size());
}
private static void addElement(List<String> playersUsingNew, String value) {
playersUsingNew.add(value);
System.out.println("After a2 hashCode = " + playersUsingNew.hashCode() + " size = " + playersUsingNew.size());
}
Each time when an element is added, a new object will be created, and playersUsing2
reference on the stack will be updated to point to that memory location. Understandable.
Now, I pass playersUsing2
to another method, so a new stack frame will be created and playersUsingNew
will also point to same memory location. And when a new element is added, a new object will be created and playersUsingNew
will point to new memory location.
But how the first stack frame, having playersUsing2
is updated to point to latest memory location?
I saw java.util.concurrent.CopyOnWriteArrayList.add(E)
implementation but couldn't understand. Is it through some native code and JVM to handle, how it happens?
Output:
Original hashCode = 1
After a1 hashCode = 3087 size = 1
After a2 hashCode = 98754 size = 2
After b1 from copyOnWriteArrayList hashCode = 98754 size = 2
After b1 hashCode = 3064461 size = 3