This is from 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. 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.
The discussion in JLS 17.5 includes this sample code:
class FinalFieldExample {
final int x;
int y;
static FinalFieldExample f;
public FinalFieldExample() {
x = 3;
y = 4;
}
static void writer() {
f = new FinalFieldExample();
}
static void reader() {
if (f != null) {
int i = f.x; // guaranteed to see 3
int j = f.y; // could see 0
}
}
}
I tried reusing this code to replicate the situation above, and here is what I have:
public class FinalFieldThread extends Thread {
public static void main(String[] args) {
ThreadA threadA = new ThreadA();
ThreadB threadB = new ThreadB();
threadB.start();
threadA.start();
//threadB.start();
}
}
class ThreadA extends Thread {
@Override
public void run() {
System.out.println("ThreadA");
FinalFieldExample.writer();
}
}
class ThreadB extends Thread {
@Override
public void run() {
System.out.println("ThreadB");
FinalFieldExample.reader();
}
}
I can test how final gets read correctly, but how can I replicate when it is not read correctly (i.e. when there is a reference to the tread before the constructor is finished?)
What you are looking for
What you are trying to test is called Don't publish the "this" reference during construction or Visibility Hazard. Read the following links in the order they are provided.
Reading
Sample Code
Output
Explanation of the output
When I access the final field in the constructor of my thread then at that time the
final
fieldx
was not properly initialized, and that's why we are getting0
.Whereas
when I access the same field in therun()
then by that time thefinal
fieldx
is initialized to3
. This is happening because of theescaping
of the reference to the object ofFinalField
. Read the 1st link I have shared, it is much more detailed.