这是一个黑客滥用事实,扩展,一个旧的不幸的设计决策。Properties
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 系统属性的范围
我刚刚写了它,有可能有一些我忽略了的东西会阻止它工作。