Properties
这是一个滥用extends事实的 hack Map
,一个旧的不幸的设计决定。
public final class JvmWideSingleton
{
private static final JvmWideSingleton INSTANCE;
static {
// There should be just one system class loader object in the whole JVM.
synchronized(ClassLoader.getSystemClassLoader()) {
Properties sysProps = System.getProperties();
// The key is a String, because the .class object would be different across classloaders.
JvmWideSingleton singleton = (JvmWideSingleton) sysProps.get(JvmWideSingleton.class.getName());
// Some other class loader loaded JvmWideSingleton earlier.
if (singleton != null) {
INSTANCE = singleton;
}
else {
// Otherwise this classloader is the first one, let's create a singleton.
// Make sure not to do any locking within this.
INSTANCE = new JvmWideSingleton();
System.getProperties().put(JvmWideSingleton.class.getName(), INSTANCE);
}
}
}
public static JvmWideSingleton getSingleton() {
return INSTANCE;
}
}
这可以被参数化,但是初始化将是惰性的并转到getSingleton()
.
Properties
是Hashtable
基于的,所以它是线程安全的(根据文档)。所以可以使用props.computeIfAbsent()
. 但我更喜欢这种方式。
另请阅读:Java 系统属性的范围
我刚刚写了它,有可能我忽略了一些东西会阻止它工作。