线程安全的单例模式的几种实现方法分享
1、饿汉式单例
public class singleton {
private final static singleton instance = new singleton();
private singleton() { }
public static singleton getinstance() {
return instance;
}
}
2、借助内部类
属于懒汉式单例,因为java机制规定,内部类singletonholder只有在getinstance()方法第一次调用的时候才会被加载(实现了lazy),而且其加载过程是线程安全的。内部类加载的时候实例化一次instance。
public class singleton {
private singleton() { }
private static class singletonholder {
private final static singleton instance = new singleton();
}
public static singleton getinstance() {
return singletonholder.instance;
}
}
3、普通加锁解决
public class singleton {
private static singleton instance = null;
private singleton() { }
public static synchronized singleton getinstance() {
if(instance == null) {
instance = new singleton();
}
return instance;
}
}
虽然解决了线程安全问题,但是每个线程调用getinstance都要加锁,我们想要只在第一次调用getinstance时加锁,请看下面的双重检测方案
4、双重检测,但要注意写法
public class singleton {
private static singleton instance = null;
private singleton() { }
public static singleton getinstance() {
if(instance == null) {
synchronzied(singleton.class) {
singleton temp = instance;
if(temp == null) {
temp = new singleton();
instance = temp
}
}
}
return instance;
}
}
由于指令重排序问题,所以不可以直接写成下面这样:
public class singleton {
private static singleton instance = null;
private singleton() { }
public static singleton getinstance() {
if(instance == null) {
synchronzied(singleton.class) {
if(instance == null) {
instance = new singleton();
}
}
}
return instance;
}
}
但是如果instance实例变量用volatile修饰就可以了,volatile修饰的话就可以确保instance = new singleton();对应的指令不会重排序,如下的单例代码也是线程安全的:
public class singleton {
private static volatile singleton instance = null;
private singleton() { }
public static singleton getinstance() {
if(instance == null) {
synchronzied(singleton.class) {
if(instance == null) {
instance = new singleton();
}
}
}
return instance;
}
}