单例模式就是保证一个类只能创建一个实例,并提供一个可以访问它的全局入口给外界访问
但是使用全局变量虽然也能给外界提供全局访问,但是它无法保证只有一个实例
经典的单例模式:
当外界需要类实例时调用getInstance,此时才根据实例是否已存在而创建然后返回,但是它存在着线程安全的隐患,如果两个线程几乎同时访问getInstance方法,而之前没有其它线程访问过,那么此时两个线程都可能判断uniqueInstance = null,然后各自创建一个实例返回,这样就违返了单例模式的初衷和设想
最简单的解决方案:
直接将getInstance方法变为线程安全的,在前面加synchronized标识
[color=red]改进的解决方案:[/color]
1、如果性能不是主要考虑因素,那么就加synchronized标识
2、用提前加载代替延迟加载,直接给实例变量new一个实例,这样当单例类被JVM加载时自动创建这个实例,并且以后只返回它的引用,如下:
3、利用“双检测锁”降低同步的使用,提供性能(此解决方案只在JAVA5之后有效)
但是使用全局变量虽然也能给外界提供全局访问,但是它无法保证只有一个实例
经典的单例模式:
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
当外界需要类实例时调用getInstance,此时才根据实例是否已存在而创建然后返回,但是它存在着线程安全的隐患,如果两个线程几乎同时访问getInstance方法,而之前没有其它线程访问过,那么此时两个线程都可能判断uniqueInstance = null,然后各自创建一个实例返回,这样就违返了单例模式的初衷和设想
最简单的解决方案:
直接将getInstance方法变为线程安全的,在前面加synchronized标识
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static synchronized= Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
[color=red]改进的解决方案:[/color]
1、如果性能不是主要考虑因素,那么就加synchronized标识
2、用提前加载代替延迟加载,直接给实例变量new一个实例,这样当单例类被JVM加载时自动创建这个实例,并且以后只返回它的引用,如下:
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
public static synchronized= Singleton getInstance() {
return uniqueInstance;
}
}
3、利用“双检测锁”降低同步的使用,提供性能(此解决方案只在JAVA5之后有效)
public class Singleton {
private volatile static Singleton uniqueInstance;
//volatile关键字保证当创建类实例时,多线程可以正确地处理该实例变量
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {//检测是否已创建实例,如果没有则进入创建实例的同步锁
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}