1

When http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight says

The values for an object's final fields are set in its constructor. Assuming the object is constructed "correctly", once an object is constructed, the values assigned to the final fields in the constructor will be visible to all other threads without synchronization. In addition, the visible values for any other object or array referenced by those final fields will be at least as up-to-date as the final fields. What does it mean for an object to be properly constructed? It simply means that no reference to the object being constructed is allowed to "escape" during construction.

Does it mean that only the thread that had seen an improperly constructed object might see it in a bad state but all other threads are fine?

For example say you have some simple code

public class Foo {
  final int x = 5;
  public Foo() {
      new Thread(() -> System.out.print(x)).start();
  }
}

Does that mean that only that thread that had seen the implicit this reference might have visibility issues, but any other threads to come that use the instance of Foo is guaranteed to see a perfectly visible Foo reference and its field x to be 5?

shmosel
  • 49,289
  • 6
  • 73
  • 138
katiex7
  • 863
  • 12
  • 23
  • Good question. I *think* the answer is yes. – shmosel Jan 03 '18 at 03:31
  • Thank you I was leaning towards the yes as well, but wanted to confirm with some others. I have so many of these subtle questions about wording and guarantees and what we can interpret them to be – katiex7 Jan 03 '18 at 03:34
  • Your best bet would be to consult the JLS, but it usually takes some study. – shmosel Jan 03 '18 at 03:35
  • I agree, I been doing that a little at a time xD It's a little frustrating though because there is just so much info and I usually need to reread a small paragraph and example for a really long time until I finally go Ahh thats what the java guys meant – katiex7 Jan 03 '18 at 03:36
  • Keep in mind that the thread seeing the incomplete object may publish it to even more threads. – Holger Jan 03 '18 at 15:40
  • Oh, that is a scary thought indeed – katiex7 Jan 03 '18 at 16:01

1 Answers1

2

The JLS states,

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

There's no indication that the visibility guarantee toward one thread would be affected by unsafe publication with respect to another thread.

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Right and also it doesnt say anything about proper construction, just that if it has finished construction then threads seeing that after complete initialization are guaranteed to see correctly initialized values for that objects final fields. I feel so much better noe – katiex7 Jan 03 '18 at 03:59