如何理解JSR-133 FAQ中final字段在新JMM下的工作机制与安全发布?
Alright, let's unpack this JSR-133 FAQ example step by step—it's a great demonstration of how final fields get special treatment under the new Java Memory Model (JMM).
First, here's the exact code snippet from the FAQ question "How do final fields work under the new JMM?":
class FinalFieldExample { final int x; int y; static FinalFieldExample f; public FinalFieldExample() { x = 3; y = 4; } static void writer() { f = new FinalFieldExample(); } static void reader() { if (f != null) { int i = f.x; int j = f.y; } } }
This is a textbook example of correct final field usage, and here's what you need to know about the guarantees it provides:
When a thread runs
reader()and findsfis not null, it will always see3forf.x. That's the critical guarantee offinalfields in JSR-133: once an object is properly constructed (meaning the constructor didn't leak a reference to the partially built object), every thread that accesses the object will see the fully initialized value of itsfinalfields. No explicit locks or synchronization are required between thewriterandreaderthreads to get this guarantee.The non-final field
yis a different story. Thereaderthread might see4(the value set in the constructor), but it could also see0(the default uninitialized value forint). There's no consistency guarantee here. Why? Because withoutfinalor synchronization, the JVM can reorder instructions. In practice, this means the assignmentf = new FinalFieldExample()might become visible to the reader thread before they = 4assignment in the constructor finishes.
The magic behind final fields is that they create a strong happens-before relationship: the initialization of the final field in the constructor happens-before any subsequent access to that field by another thread. This eliminates the risk of seeing uninitialized values for final fields, which was a loophole in older memory models.
内容的提问来源于stack exchange,提问作者azs1478963

