【发布时间】:2021-05-05 12:13:04
【问题描述】:
public class DCL {
private static DCL staticDcl;
private final DCL finalDcl;
private DCL(){
//other init operation
//the action must be last.
finalDcl = this;
}
public static DCL getDCL() {
if (staticDcl == null) {
synchronized(DCL.class) {
if (staticDcl == null) {
staticDcl = new DCL();
}
}
}
return staticDcl.finalDcl;
}
}
上面的代码在多线程环境下能否正常运行??
我想用关键字final来实现dcl而不是volatitle。
【问题讨论】:
-
您犯了一个常见错误,即未将读取的值存储到局部变量中。一个线程可能会将
staticDcl == null评估为false,因为另一个线程将非null值写入staticDcl,因此,跳过synchronized块并从@ 中的staticDcl读取null987654329@语句,由于没有同步,两次读操作没有先后顺序。
标签: java multithreading concurrency jvm