The code is from ArrayBlockingQueue,JAVA 8. The comment says:Lock only for visibility, not mutual exclusion.
final Object[] items;
int putIndex;
int count;
public ArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair);
final ReentrantLock lock = this.lock;
lock.lock(); // Lock only for visibility, not mutual exclusion
try {
int i = 0;
try {
for (E e : c) {
checkNotNull(e);
items[i++] = e;
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new IllegalArgumentException();
}
count = i;
putIndex = (i == capacity) ? 0 : i;
} finally {
lock.unlock();
}
}
I think the lock guarantees the visibility of count
&putIndex
.
But why dont use volatile
?