Java Final 关键字与缓存相关的语义

标签 java synchronization final

Java Final 关键字在缓存方面的行为是什么?

引用自:jsr133-faq

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.

当它说与最终字段一样最新时,我不明白它指的是什么。:

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.

我的猜测是,例如:

public class CC{
    private final Mutable mutable; //final field
    private Other other;           //non-final field

    public CC(Mutable m, Other o){
        mutable=m;
        other=o;
    }
}

当构造函数 CC 返回时,除了 mutable 的指针值之外,以 m 为根的对象图上的所有值(如果存在于本地处理器缓存中)都将被刷新到主内存。并且同时将其他处理器的本地缓存对应的缓存线标记为Invalid。

是这样吗?在装配中它是什么样子的?他们实际上是如何实现的?

最佳答案

Is that the case?

实际的保证是,任何可以看到使用该构造函数创建的 CC 实例的线程都保证可以看到 mutable 引用以及 CC 的状态截至构造函数完成时>可变对象的字段。

它不保证 Mutable 实例闭包中所有值的状态都是可见的。但是,在构造函数完成之前执行构造函数的线程所做的任何写入(无论是否在闭包中)都将可见。 (通过“发生之前”分析。)

请注意,该行为是根据一个线程保证看到的内容来指定的,而不是根据缓存刷新/失效来指定。后者是实现规范所需行为的一种方式。可能还有其他方法。

What does it look like in assembly?

这将是特定于版本/平台/等的。如果您想研究您的硬件的 native 代码是什么样子,有一种方法可以让 JIT 编译器转储编译后的代码。

How do they actually implement it?

见上文。

关于Java Final 关键字与缓存相关的语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40691377/

相关文章:

java - 为什么我的字符串到字符串比较失败?

iphone - iOS iPhone如何处理 "User can use app from multiple devices"这样的要求?

windows - 在 XP 上,同步文件和文件夹的最佳方式

java - Java 如何跨实例处理 Final 字段?

java - Intellij Idea 建议尽可能将所有内容设置为 final,为什么?

javac 根据赋值方法不同地处理 static final

java - Android、Eclipse : Item in . xml 布局未在图形布局中显示

java - JavaFX运行时主要方法

java - 在数组的数组中查找模式

google-chrome - 与 Service Worker 的定期后台同步支持