作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
是否保证每个线程都看到非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/
我是一名优秀的程序员,十分优秀!