这个Demo有2个地方可能造成数组越界
(1)BaseLine本身中的index++是线程不安全的
class BaseLine extends Accumulator {
{ id = "BaseLine"; }
@Override
public void accumulate() {
value += preLoaded[index++];
if(index >= SIZE) index = 0;
}
@Override
public long read() { return value; }
}
解决办法 :
preLoaded[(index++)%SIZE];
(2)index.getAndIncrement()和index.set(0)没有同步
首先index.getAndIncrement()是线程安全的 , i+1也没什么问题 , 但是index.getAndIncrement()和index.set(0)不是同步的
class AtomicTest extends Accumulator {
{ id = "Atomic"; }
private AtomicInteger index = new AtomicInteger(0);
private AtomicLong value = new AtomicLong(0);
@Override
public void accumulate() {
// Oops! Relying on more than one Atomic at
// a time doesn't work. But it still gives us
// a performance indicat