I reviewed the OpenJDK source code CopyOnWriteArrayList , and it seems that all write operations are protected by the same lock, and read operations are not protected at all. As I understand it, under JMM, all calls to a variable (both read and write) should be protected by locking or reordering.
For example, the set(int, E) method contains these lines (under lock):
int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len); newElements[index] = element; setArray(newElements);
The get(int) method, on the other hand, has only return get(getArray(), index); .
In my understanding of JMM, this means that get can observe the array in an inconsistent state if operators 1-4 reorder as 1-2 (new) -4-2 (copyOf) -3.
Do I understand JMM correctly or is there any other explanation why CopyOnWriteArrayList is thread safe?
java concurrency data-structures java-memory-model
Fixpoint Jun 01 '10 at 15:01 2010-06-01 15:01
source share