提问人:sevengold 提问时间:1/2/2023 最后编辑:sevengold 更新时间:1/2/2023 访问量:45
“命名”的静态初始值设定项是否有效 Java?[关闭]
Is a "named" static initializer valid Java? [closed]
问:
我只听说过语法为“”的静态初始值设定项。
但是在Cay Horstmann的《Core Java》一书中,有一些代码是这样的:(static {...}
private static Holder {...}
)
12.4.13 按需初始化 有时,您有一个数据结构,您只想在第一次需要时对其进行初始化。并且您希望确保初始化只发生一次。与其设计自己的机制,不如利用虚拟机在首次使用类时只执行一次静态初始值设定项这一事实。虚拟机通过锁来确保这一点,因此您不必自己编程。
public class OnDemandData {
// private constructor to ensure only one object is constructed
private OnDemandData() {}
public static OnDemandData getInstance() {
return Holder.INSTANCE;
}
// only initialized on first use, i.e. in the first call to getInstance
private static Holder {
// VM guarantees that this happens at most once
static final OnDemandData INSTANCE = new OnDemandData();
}
}
该代码无法编译。你会得到
/OnDemandData.java:12: error: <identifier> expected
private static Holder {
^
/OnDemandData.java:14: error: illegal start of expression
static final OnDemandData INSTANCE = new OnDemandData();
^
/OnDemandData.java:17: error: class, interface, enum, or record expected
}
^
3 errors
那么,它是什么?
答:
3赞
knittl
1/2/2023
#1
这是一个错别字,它应该是一个静态嵌套类():private static class Holder
public class OnDemandData {
// private constructor to ensure only one object is constructed
private OnDemandData() {}
public static OnDemandData getInstance() {
return Holder.INSTANCE;
}
// only initialized on first use, i.e. in the first call to getInstance
private static class Holder {
// VM guarantees that this happens at most once
static final OnDemandData INSTANCE = new OnDemandData();
}
}
有关此技术的解释,请参见 Java Singleton with an inner class - what guarantees thread safety?。
评论
OnDemandData
static {...}
static
Holder