我的 Property Loader 单例线程安全吗?
Is my PropertyLoader singleton threadsafe?
由于意外的 属性 值,我收到错误消息,我正在尝试缩小原因范围。 属性 通过以下示例从文件加载 class:
public final class PropertyLoader {
private enum Instances{
ELVIS;
private final PropertyLoader loader;
Instances() {
this.loader = new PropertyLoader();
}
}
private boolean isPropertyEnabled;
private PropertyLoader() {
loadProperties();
}
public static PropertyLoader getInstance() {
Instances.ELVIS.loader;
}
private void loadProperties() {
this.isPropertyEnabled = loadPropertyFromFile(FILE, "enabled");
//... more properties
}
public boolean isPropertyEnabled() {
// eventually returns unexpected value
return this.isPropertyEnabled;
}
}
这个实现是线程安全的吗?如果没有,如何在不更改接口的情况下改进实现?是否有有效的策略来测试此 class 的并发问题?
它是线程安全的。因为所有的初始化基本上都是在class初始化的时候完成的。因此,在 class 加载完成之前,两个线程无法从对象中获取数据。
由于意外的 属性 值,我收到错误消息,我正在尝试缩小原因范围。 属性 通过以下示例从文件加载 class:
public final class PropertyLoader {
private enum Instances{
ELVIS;
private final PropertyLoader loader;
Instances() {
this.loader = new PropertyLoader();
}
}
private boolean isPropertyEnabled;
private PropertyLoader() {
loadProperties();
}
public static PropertyLoader getInstance() {
Instances.ELVIS.loader;
}
private void loadProperties() {
this.isPropertyEnabled = loadPropertyFromFile(FILE, "enabled");
//... more properties
}
public boolean isPropertyEnabled() {
// eventually returns unexpected value
return this.isPropertyEnabled;
}
}
这个实现是线程安全的吗?如果没有,如何在不更改接口的情况下改进实现?是否有有效的策略来测试此 class 的并发问题?
它是线程安全的。因为所有的初始化基本上都是在class初始化的时候完成的。因此,在 class 加载完成之前,两个线程无法从对象中获取数据。