// correct multithreaded version
class foo {
private helper helper = null;
public synchronized helper gethelper() {
if (helper == null)
helper = new helper();
return helper;
}
// other functions and members...
}
第二种,使用iodh(initialization on demand holder)
利用static块做初始化,如下定义一个私有的静态类去做初始化,或者直接在静态块代码中去做初始化,能保证对象被正确构造前对所有线程不可见。
class foo {
private static class helpersingleton {
public static helper singleton = new helper();
}
public helper gethelper() {
return helpersingleton.singleton;
}
// other functions and members...
}
第三种,急切实例化(eager initialization)
class foo {
public static final helper singleton = new helper();
// other functions and members...
}
class foo {
private static final helper singleton = new helper();
public helper gethelper() {
return singleton;
}
// other functions and members...
}
第四种,枚举单例
public enum singletonclass {
instance;
// other functions...
}
// lazy initialization 32-bit primitives
// thread-safe if computehashcode is idempotent
class foo {
private int cachedhashcode = 0;
public int hashcode() {
int h = cachedhashcode;
if (h == 0) {
h = computehashcode();
cachedhashcode = h;
}
return h;
}
// other functions and members...
}
// works with acquire/release semantics for volatile
// broken under current semantics for volatile
class foo {
private volatile helper helper = null;
public helper gethelper() {
helper h = helper;
if (helper == null) {// first check (no locking)
synchronized (this) {
h = helper;
if (helper == null)
helper = h = new helper();
}
}
return helper;
}
}