单例模式
懒汉式
线程不安全
public class Singleton01 {
private static Singleton01 singleton01;
private Singleton01() {
//私有化构造器
}
public static Singleton01 getInstance() {
//调用时才创建
if (singleton01 == null)
singleton01 = new Singleton01();
return singleton01;
}
}
线程安全
public class Singleton01 {
private static Singleton01 singleton01;
private Singleton01() {
//私有化构造器
}
//创建单例时加上同步锁,保证线程安全
public static synchronized Singleton01 getInstance() {
//调用时才创建
if (singleton01 == null)
singleton01 = new Singleton01();
return singleton01;
}
}
饿汉式
public class Singleton02 {
// 在类装载时就实例化,通过classloader机制保证线程安全,但在类加载时就初始化,浪费内存。
private static Singleton02 singleton02 = new Singleton02();
private Singleton02() {
//私有化构造器
}
public static Singleton02 getInstance() {
return singleton02;
}
}
双重检验锁
public class Singleton03 {
//使用volatile关键字,避免jvm重排序
private volatile static Singleton03 singleton03;
private Singleton03() {
//私有化构造器
}
//采用双锁机制,安全且在多线程情况下能保持高性能。
public static Singleton03 getInstance() {
if (singleton03 == null) {
//使用同步锁,保证线程安全
synchronized (singleton03.class) {
singleton03 = new Singleton03();
}
}
return singleton03;
}
}
由于singleton=new Singleton()
对象的创建在JVM中可能会进行重排序,在多线程访问下存在风险,使用volatile
修饰signleton
实例变量有效,解决该问题 。
静态内部类
public class Singleton04 {
private Singleton04(){
//私有化构造器
}
//通过静态内部类,通过classloader机制保证线程安全,同时也实现懒加载
private static class SingletonHolder{
private static final Singleton04 singleton04 =new Singleton04();
}
public static Singleton04 getInstance(){
return SingletonHolder.singleton04;
}
}
枚举
这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化。它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。
不能通过 reflection attack 来调用私有构造方法。
public enum Singleton05 {
INSTANCE;
}
防止破坏
防反射、防克隆、防反序列化。
public class Singleton06 implements Serializable, Cloneable {
private static final long serialVersionUID = 6125990676610180062L;
private static volatile Singleton06 singleton06;
//采用双锁机制,安全且在多线程情况下能保持高性能。
public static Singleton06 getInstance() {
if (singleton06 == null) {
//使用同步锁,保证线程安全
synchronized (Singleton06.class) {
singleton06 = new Singleton06();
}
}
return singleton06;
}
private Singleton06 (){
//如果已存在,直接抛出异常,防止反射,保证只会被new一次
if (singleton06 != null) {
throw new RuntimeException("对象已存在,不可重复创建");
}
}
@Override
//重写clone(),直接返回单例对象,防止克隆破环
protected Object clone() throws CloneNotSupportedException {
return singleton06;
}
//添加readResolve(),返回Object对象,防止序列化破环
private Object readResolve() {
return singleton06;
}
}