我正在使用静态代码块来初始化我所拥有的注册表中的某些控制器.因此,我的问题是,我可以保证这个静态代码块只在首次加载类时才会被调用一次吗?我知道我无法保证何时会调用此代码块,我猜它是在Classloader首次加载它时.我意识到我可以在静态代码块中同步类,但我的猜测实际上这是怎么回事?
简单的代码示例是;
class FooRegistry {
static {
//this code must only ever be called once
addController(new FooControllerImpl());
}
private static void addController(IFooController controller) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
或者我应该这样做;
class FooRegistry {
static {
synchronized(FooRegistry.class) {
addController(new FooControllerImpl());
}
}
private static void addController(IFooController controller) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud) java static multithreading synchronization static-initializer
我有一个关于Enum的问题.
我有一个enum类,如下所示
public enum FontStyle {
NORMAL("This font has normal style."),
BOLD("This font has bold style."),
ITALIC("This font has italic style."),
UNDERLINE("This font has underline style.");
private String description;
FontStyle(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道这个Enum对象何时被创建.
枚举看起来像'静态最终'对象,因为它的值永远不会改变.因此,在此目的中,仅在编译时初始化是有效的.
但它在顶层调用自己的构造函数,所以我怀疑它可以在我们调用它时生成,例如,在switch语句中.
如果我在枚举类型中有一堆枚举实例,并且如果我第一次访问它的实例,那么它的所有剩余实例也会同时初始化.有没有办法在第一次访问时初始化枚举实例?