简体   繁体   中英

Safe publication of array of objects through a volatile reference

Does the following code do safe publication?

public MyThread extends Thread {
    @Override
    public void run(){
        for(int i=0; i < 100; i++){
            MyObject[] array = new MyObject[16];

            for(int j=0; j < 16; j++){
                array[i] = new MyObject(j);
                array[i].memberAttribute++;
            }

            // At this point the array is assigned to a shared volatile 
            // MyObject[] ref or put inside a concurrent collection 
        }
    }
}

Does Happens-before here apply to every newly created object or only to the array itself?

Even if the field that will hold j inside MyObject is not final ?

Yes, that's a safe publication, assuming you also properly read the reference to array afterwards (eg through the same volatile variable, or under the same lock, or from the same collection). All writes to array and to MyObject in your code happens-before any read through the published reference, including the reads of array elements.

Counter-example: if you have published array early on, say, right after new MyObject[16] , then happens-before between the writes in the loop and reads through the published reference would be absent.

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