单例模式的七种写法

单例模式的七种写法

1. 饿汉式

线程安全 比较好的一种写法

且利用 jvm的双亲委派机制 保证线程问题(只加载一次)

缺点:不管用没用到 都会被加载到jvm中

public class EHanShiSingleton{
    private static final EHanShiSingleton INSTANCE = new EHanShiSingleton();
    
	private EHanShiSingleton(){};
   
	public static EHanShiSingleton getInstance(){
    	return INSTANCE;
	}
}

2. 普通 懒汉式

缺点:多线程中会被多次实例化

public class LanHanShiSingleton{
    private static LanHanShiSingleton INSTANCE = null;

    private LanHanShiSingleton(){};

    public static LanHanShiSingleton getInstance(){
        if(INSTANCE == null){
            INSTANCE = new LanHanShiSingleton();
        }
        return INSTANCE;
    }
}

3. 加锁 懒汉式

缺点:还是在多线程中会被多次实例化 只是排队了

public class LanHanShiSingleton{
    private static LanHanShiSingleton INSTANCE = null;

    private LanHanShiSingleton(){};

    public static LanHanShiSingleton getInstance(){
        if(INSTANCE == null){
            // 加锁
            synchronized(LanHanShiSingleton.class){
                INSTANCE = new LanHanShiSingleton();
            }
        }
        return INSTANCE;
    }
}

4. 双检锁 懒汉式

缺点:浪费资源、效率不高

public class LanHanShiSingleton{
	// volatile 防止指令重排
    private static volatile LanHanShiSingleton INSTANCE = null;

    private LanHanShiSingleton(){};

    public static LanHanShiSingleton getInstance(){
        if(INSTANCE == null){
            synchronized(LanHanShiSingleton.class){
                // 加锁后 二次判断
                if(INSTANCE == null){
                    INSTANCE = new LanHanShiSingleton();
                }
            }
        }
        return INSTANCE;
    }
}

5. CAS乐观锁 懒汉式

缺点:CAS存在忙等的问题,可能会造成CPU资源的浪费。

public class LanHanShiSingleton{
    private static final AtomicReference<LanHanShiSingleton> INSTANCE = new AtomicReference<>();

    private LanHanShiSingleton(){};

    public static LanHanShiSingleton getInstance(){
        for(;;){
            if(INSTANCE.get()==null){
                LanHanShiSingleton NEW_INSTANCE = new LanHanShiSingleton();
                INSTANCE.compareAndSet(null,NEW_INSTANCE);
            }
        }
        return INSTANCE.get();
    }
}

6. 内部类 单例

利用 内部类 实现懒加载

利用 jvm的双亲委派机制 保证不会在多线程中重复加载

public class Singleton{
    private Singleton() {}

    private final static GetSingleton() {
        private final static Singleton INSTANCE = new Singleton();
    }

    private static Singleton getInstance(){
        return GetSingleton.INSTANCE;
    } 
}

7.《Effective Java》 作者推荐版 单例模式

利用枚举类实现单例模式。

同时枚举类也自动提供了序列化机制,只是枚举类无法实现继承,所以如果想要扩展就需要通过接口的方式实现。

public enum Singleton{
    INSTANCE;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值