Is volatility required?

if I have a byte queue where it is expected that there will be one thread maker, another consumer:

class ByteQueue{
    byte[] buf;
    /*volatile?*/ int readIdx;
    /*volatile?*/ int writeIdx;
    Runnable writeListener;
    Runnable readListener;
    // ...
    void write( byte[] b ){
        int wr = writeIdx;
        int rd = readIdx;
        // check consistency and free space using wr+rd
        // copy to buf, starting at wr, eventually wrap around
        // update writeIdx afterwards
        writeIdx = ( wr + b.length ) % buf.length;
        // callback to notify consumer for data available
        writeListener.run();
    }
    void read( byte[] b ){
        int wr = writeIdx;
        int rd = readIdx;
        // check consistency and available data using wr+rd
        // copy buf to b, starting at rd, eventually wrap around
        // update readIdx afterwards
        readIdx = ( rd + b.length ) % buf.length;
        // callback to notify producer for free space available
        readListener.run();
    }
    int available() { return (writeIdx - readIdx) % buf.length; }
    int free() { return buf.length - available() -1; }
    // ...
}

This type of queue does not require synchronization.
readIdx is modified only through the stream of readers,
writeIdx only by the stream of writing.

readIdx == writeIdx means that there is no content.
And the queue can only process data buf.length-1 bytes.

Are volatiles required or can they be eliminated, since only one stream is a modifier of one integer state?

THX Frank

+4
source share
3 answers

, . volatile JVM, , .

buf. buf , , . , , buf .

+5

volatile. , , readIdx. volatile, , .

, readIdx ( writeIdx ) rd ( wr). , - , .

+2

, , , (, , ).

, , , LMAX disruptor.

+1

All Articles