Search code examples
java.util.concurrentjavajava-memory-model

Why is volatileWrite necessary inside Atomic{Type}Array constructor


For example the constructor that takes array size of java.util.concurrent.atomic.AtomicLongArray is defined as following:

    public AtomicLongArray(int length) {
    array = new long[length];
    // must perform at least one volatile write to conform to JMM
    if (length > 0)
        unsafe.putLongVolatile(array, rawIndex(0), 0);
}

Snippet taken from AtomicLongArray.java.

Why is volatileWrite necessary inside this constructor when array field is final ?


Solution

  • There is no need for it, and this line of code was removed in later versions of of the JDK

    This how it looks in JDK 1.7 and 1.8

    public  AtomicLongArray(int length) {
         array = new long[length];
    }