一、 单例模式概述
Java中单例模式的定义是:一个类只有一个实例,而且自行实例化并且向整个系统提供这个实例。
优点:由于单例模式在内存中只有一个实例,减少了内存开支和系统的性能开销;单例模式可以避免对资源的多重占用。
二、单例模式的几种形式
1. 饿汉式单例
public class Singleton {
private static final Singleton singleton= new Singleton();
private Singleton(){
}
public Singleton getSingleton(){
return singleton;
}
}
饿汉式是线程安全的,在类开始加载的时候就完成了单例的初始化。线程安全在java并发编程实战中是这样定义的:当多个线程访问某个类时,不管运行时环境采用何种调度方式或者这些线程将如何交替执行,并且在主调代码中不需要任何额外的同步或者协同,这个类都能表现出正确的行为,那么就称这个类是线程安全的。
2.懒汉式单例
public class Singleton {
private Singleton() {}
private static Singleton single=null;
public static Singleton getInstance() {
if (single == null) {
single = new Singleton();
}
return single;
}
}
懒汉式不是线程安全的,并发环境下,可能出现多个single对象。要实现线程安全,可以采用双重锁:
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
三、单例模式在spring中的应用
DefaultSingletonBeanRegistry类中的getSingleton方法:
/** Cache of singleton objects: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);
/** Cache of singleton factories: bean name --> ObjectFactory */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
/** Cache of early singleton objects: bean name --> bean instance */
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// map缓存中查看是否存在实例
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
从上面的代码中可以看出spring在获取单例bean的时候,采用了双重判断加锁的单例模式,首先尝试从map缓存singletonObjects中获取实例,如果获取不到,对singletonObjects加锁,再到map缓存earlySingletonObjects里面获取,如果还是为null,就创建一个bean,并放到earlySingletonObjects中去。