As I can see in the set method of COWArrayList, It acquires lock before performing mutative operaitons like "set".
For e.g:
public E set(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
E oldValue = get(elements, index);
if (oldValue != element) {
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len);
newElements[index] = element;
setArray(newElements);
} else {
// Not quite a no-op; ensures volatile write semantics
setArray(elements);
}
return oldValue;
} finally {
lock.unlock();
}
}
I do have two questions here, which i could not figure out:
- Acquiring lock will ensure other threads will see the updated state. Why volatile keyword is required with underlying array
- Why storing value of lock in final local variable "final ReentrantLock lock = this.lock;" instead of directly performing operation "this.lock.lock".