简体   繁体   中英

How are the final multi-threading guarantees and the memory model related in Java?

The memory model is defined in 17.4. Memory Model .

The final field multi-threading guarantees are given in 17.5. final Field Semantics .

I don't understand why these are separate sections.

AFAIK both final and the memory model provide some guarantees.
And any real program execution must respect both guarantees.
But it's now clear whether the final guarantees work for the intermediate executions used to validate causality requirements in 17.4.8. Executions and Causality Requirements .

Another unclear moment is that 17.5.1. Semantics of final Fields defines a new "special" happens-before , which differs from the happens-before in the memory model:

This happens-before ordering does not transitively close with other happens-before orderings.

If these are the same happens-before , then the happens-before isn't a partial order anymore (because it isn't transitive).
I don't understand how this doesn't break things.

If these are different happens-before , then it's not clear what the one in 17.5. final Field Semantics does.
The happens-before in 17.4. Memory Model is used to restrict what a read can return:

Informally, a read r is allowed to see the result of a write w if there is no happens-before ordering to prevent that read.

But 17.5. final Field Semantics is a different section.

The special 'final field guarantees' part was a later add-on. Documentation sometimes follows the quirks of history - possibly, had the 'final field guarantee' issue been discovered prior to the first release of the JMM, the documentation would have been structured differently.

In other words, you're asking for 'why is this stuff in a separate chapter' and perhaps the answer is: "Because it was added in a later version of java, and therefore it was written at a completely different time; a new chapter is presumably the simplest way to add some more documentation". We're talking about decades ago at this point, of course.

§17.5 explains its purpose. Quote:

The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and 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.

In other words, in the distant past, you could do this:

Thread A:

  • Make a new object. The constructor is 'well behaved' 1
  • Communicate the ref to this new object to another thread. Possibly in an unsafe way.

Thread B:

  • The receiving thread gets the correct ref (either because you did it safely with synchronization, ie happens-before relationship set up properly, or because you did it unsafely, but the JMM does not guarantee that unsafe code fails to work: It may still work).
  • It calls a method of this object.
  • Said object witnesses a final -marked field that isn't initialized, because the initialization did occur in thread A, but no happens-before relationship exists, and re-ordering and other shenanigans means that this thread doesn't see it yet.

This is extremely annoying. Part of the point of immutable classes is that you can more or less print out the JMM and set it on fire. You just don't need to care about virtually every tricky rule in it if your system is an amalgamation of immutable types. Except, it didn't actually work out that way prior to the existence of §17.5

The JMM as a general principle is designed to give any JVM implementations as few 'handcuffs' as possible whilst making developing for the JVM as uncomplicated as possible. It's a fine line - for example, had the JMM simply stated: "The JVM is free to re-order whatever it wants at any time, and cache whatever it wants, at any time, for whatever duration it wants", then writing JVMs that run code quickly and according to spec would be 'easier' (JVM impls would be faster), but, writing multithreaded code that actually does what you intended it to becomes borderline impossible. On the flipside, the JMM could also have guaranteed that re-ordering in the JVM is impossible to observe regardless of circumstance or architecture. But then JVMs would be slow as molasses, see Python and its much maligned global interpreter lock.

The JMM tries to be the happy compromise. And §17.5 is written with the same spirit.

It basically says:

  • You CAN rely on the notion that any well-behaved construction means that final fields will just work out without having to worry about happens-before relationships whatsoever.
  • However, you CANNOT, at all, rely on HOW the JVM implements the guarantee. In particular, we have defined what you can exactly rely on in terms of Happens-Before, but it's not the same HB that the rest of the JMM talks about. We guarantee you that well-behaved construction means final fields won't be an issue but that's as far as our guarantee goes: You cannot use this guarantee to then force other guarantees out of the JMM; you can't use this mechanism as a wonky way to establish HB for other stuff, for example.

The JMM buys room to maneuver for JVM impls. Whether a JVM impl actually uses it, is up to the JVM implementor. In other words, a JVM implementor may well decide to implement §17.5 by using the same locking mechanisms it uses to guarantee the HB stuff in §17.4, and thus effectively you can apply properties like 'HB relationships are transitive'. The point of the JMM is partly to allow JVM impls to take some pretty drastically different approaches to how the guarantees it dictates are in fact guaranteed. That's because JVMs have to be written so that they can run code about as fast as native code could on a wide variety of hardware, whilst still being a target platform that isn't impossible to develop for.

Quite the tightrope walk. This is the primary underlying explanation for the JMM can be obtuse and bizarre at times.

[1] A 'well behaved' constructor:

  • Does not pass its own reference ( this ) to any code outside of its own class during construction.
  • Does not invoke any of its own instance methods that then read its own fields (or, especially problematic, which can be overridden by subclasses, whose implementation uses its own fields). Basically: Calling any non-final method is an instant "You are not well behaved" violation.
  • Does not send any object refs of things I wishes to store in fields to code in other classes during construction. Even if it has already assigned it to the final field before doing so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM