I think I've read that the final keyword on a field guarantees that if thread 1 instantiates the object containing the field, then thread 2 will always see the initialized value of that field if thread 2 has a reference to the object (provided it was properly constructed). It also says in the JLS that
[Thread 2] 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. (section 17.5 of JLS)
That implies that if I have class A
class A {
private final B b = new B();
private int aNotFinal = 2;
...
and class B
class B {
private final int bFinal = 1;
private int bNotFinal = 2;
...
then aNotFinal is not guaranteed to be initialized by the time thread 2 gets a reference to class A, but field bNotFinal is, because B is an object referenced by a final field, as specified in the JLS.
Do I have this right?
Edit:
A scenario where this could happen would be if we have two threads concurrently executing getA() on the same instance of a class C
class C {
private A a;
public A getA(){
if (a == null){
// Thread 1 comes in here because a is null. Thread B doesn't come in
// here because by the time it gets here, object c
// has a reference to a.
a = new A();
}
return a; // Thread 2 returns an instance of a that is not fully
// initialized because (if I understand this right) JLS
// does not guarantee that non-final fields are fully
// initialized before references get assigned
}
}
A
.