数组元素需要变化吗?如果是的话,我该怎么做呢?

时间:2015-02-12 20:56:24

标签: java concurrency visibility atomic

假设我的代码很少:

public class Test {
    final Data[] dataArray;
    final int maxSize;
    volatile long nextWriteNo;
    volatile long nextReadNo;

    public Test(int maxSize){
        this.dataArray = new Data[maxSize];
        this.maxSize = maxSize;
        this.nextWriteNo = 0L;
        this.nextReadNo = 0L;
    }

    public void write(Data data){
        synchronized (this) {
            dataArray[(int)(nextWriteNo & (maxSize - 1))] = data;
            nextWriteNo = nextWriteNo + 1L;
        }
    }

    public Data read(Data data){
        synchronized (this) {
            Data data = dataArray[(int)(nextReadNo & (maxSize -1))];
            nextReadNo= nextReadNo + 1L;
            return data;
        }
    }
}

一个线程多次调用write()方法,而其他线程多次调用read()方法。 write()方法更新数组,而read方法读取数组。全部发生在synchronized区块内。因此,对于可见性,或者在关系之前发生,数组元素(对象引用)是否需要volatile?如果是这样,我该怎么做呢?

1 个答案:

答案 0 :(得分:4)

没有理由在同步块中使用volatile。块本身保证了值的状态在读写之间保持一致。