You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何理解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).

Final Field Behavior in JSR-133

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 finds f is not null, it will always see 3 for f.x. That's the critical guarantee of final fields 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 its final fields. No explicit locks or synchronization are required between the writer and reader threads to get this guarantee.

  • The non-final field y is a different story. The reader thread might see 4 (the value set in the constructor), but it could also see 0 (the default uninitialized value for int). There's no consistency guarantee here. Why? Because without final or synchronization, the JVM can reorder instructions. In practice, this means the assignment f = new FinalFieldExample() might become visible to the reader thread before the y = 4 assignment 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:30:48