转载请注明出处:jiq•钦'stechnical Blog
1、饿汉式
- public class Singleton {
- private final static Singleton INSTANCE = new Singleton();
- private Singleton() { }
- public static Singleton getInstance() {
- return INSTANCE;
- }
- }
2、懒汉式
2.1普通加锁模式
- public class Singleton {
- private static Singleton instance = null;
- private Singleton() { }
- public static synchronized Singleton getInstance() {
- if(instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
2.2占位符模式(推荐)
属于懒汉式单例,因为Java机制规定,内部类SingletonHolder只有在getInstance()方法第一次调用的时候才会被加载(实现了lazy),而且其加载过程是线程安全的。内部类加载的时候实例化一次instance。
- public class Singleton {
- private Singleton() { }
- privatestatic class SingletonHolder {
- //内部类,第一次使用时才加载,且只能SingletonHolder类能访问
- //特别注意:static域中修改共享变量是线程安全的,由JVM保障
- static Singleton INSTANCE = new Singleton();
- }
- public static Singleton getInstance() {
- return SingletonHolder.INSTANCE;
- }
- }
2.3双重检测
普通双重检测:
- 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 Singletoninstance = null; //以volatile关键字修饰防止指令重排
- private Singleton() { } //构造函数为私有,防止被实例化
- public static Singleton getInstance() {
- if(instance == null) { //双重检测
- synchronzied(Singleton.class) {
- if(instance == null) {
- instance = new Singleton();
- }
- }
- }
- return instance;
- }
- }