Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array Synchronization (Visibility)

I am trying to understand exactly how element visibility works on arrays in java.

Given the class:

class IntList {

    private final int[] array;

    public IntList(int[] array) {
        this.array = array;
    }

    public int[] readElements() {
        return Arrays.copyof(this.array, this.array.length);
    }

}    

and the following method body for creating an instance:

int[] array = new int[length];
fillArrayWithRandomData(array); // puts data into the array from arbitrary source
return new IntList(array);

I am wondering if the elements in the IntList are guaranteed to be visible by other threads that obtain a reference to the returned IntList?

I am sure that the REFERENCE to the array will be visible because it is final but I cannot seem to find a guarantee that the elements in the array will be visible as well.

Note: The IntList class has no methods that allow the modification of the array and the array reference is not published to any other object, I am only wondering about visibility after construction.

Edit: Sorry, my class is not called String in my actual implementation. I changed the class name to IntList because there seems to be too much confusion.

Edit: The final answer I'll put here is Yes, the elements are visible.
@MikeClark found the JLS answer: JLS § 17.5 "The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are."

Thanks again!

like image 791
nikdeapen Avatar asked Nov 20 '12 19:11

nikdeapen


1 Answers

Since you are populating the array in the constructor then yes, any call to new String(int[] array) will have the array initialized by the time it returns. The final keyword will also guarantee that the most recent changes to the array parameter at the time of assignment will be visible.

like image 86
Abdullah Jibaly Avatar answered Sep 22 '22 06:09

Abdullah Jibaly