public class SingleInstance {
public SingleInstance() {
}
//饱汉模式之线程安全和效率讨论
/**
* 效率低,每次进来都要同步,尽管实例不为空了
* @return
*/
public static synchronized SingleInstance getInstance() {
if (instance == null) {
instance = new SingleInstance();
}
return instance;
}
/**
* DCL单利模式,比上一个方法提高了效率,但是线程不是绝对安全
* @return
public static SingleInstance instance;
public static SingleInstance getDCLinstance() {
if (instance == null) {
synchronized (SingleInstance.class) {
//DCL 双重校验,但是高并发中可能偶发指令集乱序问题
if (instance == null) {
instance = new SingleInstance();
}
}
}
return instance;
}
*/
//volatile在JDK1.5之后退出,防止指令集乱序
public volatile static SingleInstance instance;
public static SingleInstance getDCLinstance() {
if (instance == null) {
synchronized (SingleInstance.class) {
//DCL 双重校验,但是高并发中可能偶发指令集乱序问题
if (instance == null) {
instance = new SingleInstance();
}
}
}
return instance;
}
注意:当然也可以通过枚举来单例,因为枚举的构造函数是私有的
}