简体   繁体   中英

does array elements need to be volatile? if so, how can I make it?

Suppose I have little code like this:

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;
        }
    }
}

Where one thread will call write() method multiple times, and other thread will call read() method multiple times. write() method updates array, while read method reads array. All happens inside synchronized block. So for visibility, or happens before relationships, does array elements (object references) need to be volatile ? If so, how can I make it?

There's no reason to use volatile inside of a synchronization block. The block itself guarantees the value's state to be consistent between reads and writes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM