gpt4 book ai didi

java - 非最终初始化程序是线程安全的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:53 24 4
gpt4 key购买 nike

是否保证每个线程都看到非final字段的实例初始化器(字段等号右边的表达式)的值?例如:

class Foo {
private boolean initialized = false; // Initializer
private final Lock lock = new ReentrantLock();

public void initialize() {
lock.lock()
try {
// Is initialized always false for the first call of initialize()?
if (initialized) {
throw new IllegalStateException("already initialized");
}
// ...
initialized = true;
} finally {
lock.unlock();
}
}
}

最佳答案

在那种特定情况下你没问题,因为false 也是boolean 字段 的默认值。如果您的实例变量初始化是:

private boolean initialized = true;

那么您将无法保证线程会读取 true

请注意,如果该字段是静态的,则由于类加载语义,您将获得这样的保证。

引用:JLS 17.4.4 (强调我的)

The write of the default value (zero, false, or null) to each variable synchronizes-with the first action in every thread.
Although it may seem a little strange to write a default value to a variable before the object containing the variable is allocated, conceptually every object is created at the start of the program with its default initialized values.

关于java - 非最终初始化程序是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16980492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com