下面列出了java.util.concurrent.atomic.AtomicLongArray#weakCompareAndSetVolatile() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* get and set for out of bound indices throw IndexOutOfBoundsException
*/
public void testIndexing() {
AtomicLongArray aa = new AtomicLongArray(SIZE);
for (int index : new int[] { -1, SIZE }) {
final int j = index;
final Runnable[] tasks = {
() -> aa.getPlain(j),
() -> aa.getOpaque(j),
() -> aa.getAcquire(j),
() -> aa.setPlain(j, 1),
() -> aa.setOpaque(j, 1),
() -> aa.setRelease(j, 1),
() -> aa.compareAndExchange(j, 1, 2),
() -> aa.compareAndExchangeAcquire(j, 1, 2),
() -> aa.compareAndExchangeRelease(j, 1, 2),
() -> aa.weakCompareAndSetPlain(j, 1, 2),
() -> aa.weakCompareAndSetVolatile(j, 1, 2),
() -> aa.weakCompareAndSetAcquire(j, 1, 2),
() -> aa.weakCompareAndSetRelease(j, 1, 2),
};
assertThrows(IndexOutOfBoundsException.class, tasks);
}
}
/**
* repeated weakCompareAndSetVolatile succeeds in changing value when equal
* to expected
*/
public void testWeakCompareAndSetVolatile() {
AtomicLongArray aa = new AtomicLongArray(SIZE);
for (int i = 0; i < SIZE; i++) {
aa.set(i, 1);
do {} while (!aa.weakCompareAndSetVolatile(i, 1, 2));
do {} while (!aa.weakCompareAndSetVolatile(i, 2, -4));
assertEquals(-4, aa.get(i));
do {} while (!aa.weakCompareAndSetVolatile(i, -4, 7));
assertEquals(7, aa.get(i));
}
}