不使用synchronized和lock,如何实现一个线程安全的单例?
文章来自
loveinliuy的博客 // 每一个技术的学习,都是从模仿开始!
Home
About Me
Tags
Archives
借助ClassLoader的线程安全机制 # 枚举 ``` public enum Singleton { INSTANCE; public void whateverMethod() { } } ``` # 静态内部类 ``` public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } } ``` # 饿汉 ``` public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } } ``` 乐观锁 # CAS ``` public class Singleton { private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>(); private Singleton() {} public static Singleton getInstance() { for (;;) { Singleton singleton = INSTANCE.get(); if (null != singleton) { return singleton; } singleton = new Singleton(); if (INSTANCE.compareAndSet(null, singleton)) { return singleton; } } } } ```
Pre:
查看网络速率
Next:
jvm系列(四):jvm调优-命令篇
Please enable JavaScript to view the
comments powered by Disqus.
comments powered by
Disqus