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 (e.g. 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.