Search code examples
javaarrayssynchronizationvolatileprimitive

Is volatile needed here?


In the following hypotetical scenario and out of desire to better understand the language, is volatile required for the int[] reference?

public final class SO {

    private int[] ar = new int[10];  // is volatile needed here?
    private int idx = 0;

    public synchronized int get( int i ) {
        return ar[i];
    }

    public synchronized void append( final int val ) {
        if ( idx == ar.length ) {
            // array is too small, let's grow it
            final int[] prev = ar;
            ar = new int[ar.length+ar.length*20/100]
            System.arrayCopy(prev, 0, ar, 0, prev.length);
        }
        ar[idx++] = val;
    }

}

The only way to retrieved an int is trough a synchronized method and the only way to modify the int[] (including creating a new int[]) is also done trough a synchronized method.

I do not need to add any additional synchronization right?


Solution

  • No, volatile not needed because it is only accessed inside synchornised methods so it is already thread safe. No further thread safety is needed in your code.