45

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
  }
}
9
  • This kind of depends on how you create and pass around the instance of A. Commented Dec 2, 2014 at 16:33
  • Why would you assume that bNotFinal is "at least as up to date" as the final reference to B?
    – aioobe
    Commented Dec 2, 2014 at 16:35
  • 1
    @Sotirios - thanks, yes have added an example to my op
    – user384842
    Commented Dec 2, 2014 at 16:47
  • 1
    @aioobe - ah.. perhaps I'm misinterpreting it? I understand the JLS quote to mean that variables referenced by final fields are guaranteed to be as up to date as the final reference. This is also the way Goetz et al explain it in JCIP. They say "any variables that can be reached through the final field of a properly constructed object are guaranteed to be visible to other threads."
    – user384842
    Commented Dec 2, 2014 at 16:54
  • @aioobe b is final in class A
    – user384842
    Commented Dec 2, 2014 at 16:55

6 Answers 6

22

What you are saying is true.

Marking a field as final forces the compiler to complete initialization of the field before the constructor completes. There is no such guarantee however for non-final fields. This might seem weird, however there are many things done by the compiler and JVM for optimization purposes such as reordering instructions, that cause such stuff to occur.

The final keyword has many more benefits. From the Java Concurecncy in Practice:

Final fields can't be modified (although the objects they refer to can be modified if they are mutable), but they also have special semantics under the Java Memory Model. It is the use of final fields that makes possible the guarantee of initialization safety (see Section 3.5.2) that lets immutable objects be freely accessed and shared without synchronization.

The Books says then:

To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:

  • Initializing an object reference from a static initializer;
  • Storing a reference to it into a volatile field or AtomicReference;
  • Storing a reference to it into a final field of a properly constructed object; or
  • Storing a reference to it into a field that is properly guarded by a lock.
6
  • Marking a field as final forces the compiler to complete initialization of the field before the constructor completes. -- So the value of the b field needs to be initialized when the constructor has completed (i.e. it needs to have a reference to a B object), but is it really guaranteed that the value of b.bNotFinal is initialized when the constructor completes?
    – aioobe
    Commented Dec 2, 2014 at 16:51
  • 1
    @aioobe The JLS guarantees that, for a non-final variable v of any type except long or double, when some thread T accesses v without synchronization, it will either get the initial value, or it will get some value that was previously stored in v. The JLS does not guarantee that thread T will see the most recent value stored in v. If you must have the most recent value, or if v is of type long or double, then all accesses to v should be synchronized. Commented Dec 2, 2014 at 17:53
  • By my understanding, if a factory for class Foo were to create a Foo, pass it to the constructor of a FooHolder with a final Foo it, and then return the reference read from it, that would "publish" the contents of everything reachable from Foo, but that seems a bit clunky. Is there any more efficient way of achieving such an effect? For example, suppose one were writing a String-style class, and wished to make it so that if two String instances were discovered to contain the same characters, one would have its backing-array reference changed to use the other's array.
    – supercat
    Commented Dec 2, 2014 at 18:06
  • If the comparison function started by testing whether two strings had the same backing array, then repeated comparisons of the same strings could be expedited. On the other hand, that couldn't be done if the backing array reference were final, and if the reference isn't final then it would be necessary to do something to ensure it gets published the way it would if it were final.
    – supercat
    Commented Dec 2, 2014 at 18:08
  • @supercat: that’s an entirely different question, however, that is still possible as you can modify final instance fields using Reflection and access override. But that should not become your normal way of your work…
    – Holger
    Commented Dec 2, 2014 at 18:53
13

I think your question is answered by JLS right below the part you quote, in Section 17.5.1: Semantics of final Fields:

Given a write w, a freeze f, an action a (that is not a read of a final field), a read r1 of the final field frozen by f, and a read r2 such that hb(w, f), hb(f, a), mc(a, r1), and dereferences(r1, r2), then when determining which values can be seen by r2, we consider hb(w, r2).

Let's break it down in terms of the question:

  • w: is the write to bNotFinal by Thread 1
  • f: is the freeze action that freezes b
  • a: publish of the A object reference
  • r1: a read of b (frozen by f) by Thread 2
  • r2: a reaf of b.bNotFinal by Thread 2

We note that

  • hb(w, f): The write to bNotFinal happens before the freeze of b
  • hb(f, a): The A reference is published after the constructor is finished (i.e. after the freeze)
  • mc(a, r1): Thread 2 reads the A reference before reading A.b
  • dereferences(r1, r2): Thread 2 dereferences the value of b by accessing b.bNotFinal

The following sentence...

"then when determining which values can be seen by r2, we consider hb(w, r2)"

...then translates to

when determining which values can be seen by the read of b.bNotFinal we consider that the write to bNotFinal by Thread 1 happens before the read of b.bNotFinal.

I.e. Thread 2 is guaranteed to see the value 2 for b.bNotFinal.


A relevant quote by Bill Pugh:

The ability to see the correctly constructed value for the field is nice, but if the field itself is a reference, then you also want your code to see the up to date values for the object (or array) to which it points. If your field is a final field, this is also guaranteed. So, you can have a final pointer to an array and not have to worry about other threads seeing the correct values for the array reference, but incorrect values for the contents of the array. Again, by "correct" here, we mean "up to date as of the end of the object's constructor", not "the latest value available".

In particular this is a direct answer to the example @supercat brought up regarding illsynchronized sharing of String references.

8
  • If an object has a final field of its own type, and stores a reference to itself in that field as the last action in its constructor, having written to all of its field before that, and does not leak a reference to itself prior to that, would that be sufficient to ensure that all threads will see all of the object's fields as having been written at least once even if none of the other fields are final? Is there any way to achieve a similar effect without wasting memory for the final field?
    – supercat
    Commented Dec 2, 2014 at 23:41
  • @supercat: what you describe, is a “leaking this” as the reference you are storing in the final field is not a “properly constructed” object but the object still being under construction. So that trick won’t work as a “leaking this” voids the final field safe publication guaranty. But after all, there is no sense in trying such tricks, it’s easier to do a correct publication of the object in the first place.
    – Holger
    Commented Dec 3, 2014 at 9:13
  • @supercat, I can't say I have a clear intuition about this myself, but I suspect that what you're suggesting would work, as long as you access the object through the objects final field. (There has to be a dereferences step for the guarantee to hold.)
    – aioobe
    Commented Dec 3, 2014 at 9:54
  • @aioobe: Adding a dereference to every read would seem icky, and I can't see any plausible mechanism where it should matter, though I guess it would be theoretically possible for a conforming JVM to go out of its way to make it matter. I think it should be safe to have a factory method which, rather than returning an object directly, passes it to the constructor of a simple "holder" object which stores the reference in a public final field; I think if the factory method returns the contents of that public field, that would create all the necessary "happens-before" relationships.
    – supercat
    Commented Dec 3, 2014 at 14:30
  • @aioobe: Still, creating a new temporary object just for the purpose of being able to stick a reference into a final field and read it out, seems like an absurd amount of work. I wonder if Oracle had added in Java 9, or will add, a native method something like static void PublishAllIndirectReferences(Object o); which would behave equivalently? Also, I wonder if they'll add any "method" with the semantics that would imply that code must actually read things from memory at least sometimes, though not necessarily every time the "method" is called, for things like...
    – supercat
    Commented Dec 3, 2014 at 14:36
3

It's worth mentioning that final here serves the same purpose as volatile in terms of visibility of values to threads. That said, you cannot use both final and volatile on a field as they are redundant to each other. Back to your question. As others have pointed out your assumption is wrong as JLS only guarantees the visibility of the reference to B, not the non-final fields defined in B. However, you can make B behaves in the way you want it to behave. One solution is to declare bNotFinal as volatile if it can't be final.

3
  • 1
    The semantics of final and volatile are different; if code writes characters into a char[], stores a reference to a final field, and never again writes to the array, any thread which reads the field is guaranteed to see the characters that were written. I don't think such a guarantee would hold if the field were merely `volatile.
    – supercat
    Commented Dec 2, 2014 at 18:38
  • 2
    @supercat: the same does work for volatile; all writes made by the thread before writing the volatile reference happens-before the write to the volatile reference.
    – Holger
    Commented Dec 2, 2014 at 18:57
  • 1
    @neurite, How did this answer get 3 upvotes when it completely contradicts the other answers?
    – Pacerier
    Commented May 17, 2020 at 14:34
2
class A {
    private final B b = new B();
}

The above line only guarantees that b will be initialized when you access b from an instance of A. Now the detail of b's initialization or any instantiation of B is completely dependent on how B is defined and in this case it may get initialized as per JLS or may not.

So, if you do A a = new A(); from one thread and somehow manage to read a.b from another thread, it is guaranteed you will not see null if a is not null but b.bNotFinal may be still zero.

3
  • 1
    What if class A had a constructor which stored a passed-in B to a final field, and class B had a factory method public B makeB(...) { B b = new B(...); A a = new A(b); return a.b; } I would think if B's constructor was only invoked via that factory method, that would imply that any of that B's fields (final or not) which were written in B's constructor would be seen as having been written at least once by anything, on any thread, which could get a reference to that B.
    – supercat
    Commented Dec 2, 2014 at 18:20
  • @supercat First, if it is a static factory method, anyone calling that method acquires the intrinsic lock for the Class. Second, from your comment, you are making it sequential not concurrent. Or if an another thread has access at the point A a= new A(b), it is done.
    – yadab
    Commented Dec 3, 2014 at 1:33
  • @yadab, How did this answer get 2 upvotes when it completely contradicts the other answers?
    – Pacerier
    Commented May 17, 2020 at 14:35
2

There is a memory barrier inserted after a final assignment (it's a store fence), this is how you guarantee that the other threads will see the value that you assign. I like the JLS and how it says that things are done with happens-before/after and guarantees of the final, but to me, the memory barrier and it's effects are much simpler to grasp.

You should really read this : Memory barriers

1

"JSR 133 (Java Memory Model) FAQ, Jeremy Manson and Brian Goetz, February 2004" describes how does final field work.

QUOTE:

The goals of JSR 133 include:

  • A new guarantee of initialization safety should be provided. If an object is properly constructed (which means that references to it do not escape during construction), then all threads which see a reference to that object will also see the values for its final fields that were set in the constructor, without the need for synchronization.
1
  • Regarding your quote: then all threads which see a reference to that object will also see the values for its final fields that were set in the constructor, without the need for synchronization The question here is whether this holds also for non-final fields reachable through a final reference.
    – aioobe
    Commented Dec 3, 2014 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.