DZone refcard titled \"Core Java Concurrency\" states:
Once set, final field values cannot be changed. Marking an object reference field as final do
The guarantee is stronger than you appear to think. The final field semantics apply even to mutable objects that are assigned to final fields (with the usual restrictions). SO extending your example to make A.b
private and B
mutable (but not externally mutable).
public class A {
private final B b = new B();
public Integer get() { return b.c; }
}
public class B {
public Integer c = 10;
}
In this case, A.get
will never return null
even under unsafe publication. Of course this example is completely abstract and therefore meaningless. Typically it is important for arrays (for instance in String
) and collections.