I am learning the java concurrent package.
After reading the source of CopyOnWriteArrayLis, I have a following question.
private boolean addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
// Here is my question.
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
if (snapshot != current) {
// Optimize for lost race to another addXXX operation
int common = Math.min(snapshot.length, len);
for (int i = 0; i < common; i++)
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
if (indexOf(e, current, common, len) >= 0)
return false;
}
Object[] newElements = Arrays.copyOf(current, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
My question is why the Optimize is needed ?
Of cource, I have googled myself, and the answer is always to make it right when other threads may have added new elements.
But how to explain the lock.lock()? When one thread has got the lock, how can other threads add new elements ?
I know may be it is a stupid question, but I am really confusing about that.