首页 > 学院 > 开发设计 > 正文

Kata系列之双重检查锁、静态工厂、枚举类实现单例类

2019-11-08 18:49:42
字体:
来源:转载
供稿:网友

package test;/** * 双重检查锁实现单例类 * @author huawangxin * 2017年2月16日 下午2:28:27 * * 代码会检查两次单例类是否有已存在的实例,一次加锁一次不加锁,一次确保不会有多个实例被创建。 * 该模型存在的问题: * 解决方案:在JDK1.5中,java修复了其内存模型的问题。volatile修饰符修饰object变量, * 能保证先行发生关系,所有的写(write)都将先行发生于读(read)。在JDK1.5之前,这种方法会有问题。 *  */public class TestSingleton {    PRivate static TestSingleton object;    public static TestSingleton getInstance() {          if (object == null) {              synchronized (object) {                  if (object == null) {                      object = new TestSingleton();                  }              }          }          return object;      }}

package test;/** * 双重检查锁实现单例类【改进版】 * @author huawangxin * 2017年2月16日 下午2:28:27 *  */public class TestSingleton2 {    private static TestSingleton2 instance = null;      private TestSingleton2() {}      private static synchronized void syncInit() {          if (instance == null) {              instance = new TestSingleton2();          }      }      public static TestSingleton2 getInstance() {          if (instance == null) {              syncInit();          }          return instance;      }}

package test;/** * 枚举实现单例类【改进二版】 * @author huawangxin * 2017年2月16日 下午2:28:27 * 该方式为目前最好的原因:1.线程安全 2.不会因为序列化而产生新实例 3.防止反射攻击 *  */public enum Work {    INSTANCE;    public TestSingleton singleWrite() {        return new TestSingleton();    }

    private Object readResolve(){        return INSTANCE;    }}public class Test{    public static void main(String[] args) {        TestSingleton write = Work.INSTANCE.singleWrite();    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表