分享

Java线程安全的单例模式的几种实现 | IT江湖

 jnstyle 2015-06-25
线程安全的单例模式实现有几种思路

1、饿汉式

Java
1
2
3
4
5
6
7
8
9
public class Singleton {
   private final static Singleton INSTANCE = new Singleton();
   private Singleton() { }
   public static Singleton getInstance() {
      return INSTANCE;
   }
}

2、借助内部类

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton {
  
   private Singleton() { }
   private static class SingletonHolder {
      private final static Singleton INSTANCE = new Singleton();
   }
   public static Singleton getInstance() {
      return SingletonHolder.INSTANCE;
   }
}
属于懒汉式单例,因为Java机制规定,内部类SingletonHolder只有在getInstance()方法第一次调用的时候才会被加载(实现了lazy),而且其加载过程是线程安全的。内部类加载的时候实例化一次instance。

3、普通加锁解决

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Singleton {
   private static Singleton instance = null;
   private Singleton() { }
  
   public static synchronized Singleton getInstance() {
      if(instance == null) {
         instance = new Singleton();
      }
      return instance;
   }
}
虽然解决了线程安全问题,但是每个线程调用getInstance都要加锁,我们想要只在第一次调用getInstance时加锁,请看下面的双重检测方案

4、双重检测,但要注意写法

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class Singleton {
   private static Singleton instance = null;
   private Singleton() { }
   public static Singleton getInstance() {
      if(instance == null) {
         synchronzied(Singleton.class) {
            Singleton temp = instance;
            if(temp == null) {
               temp = new Singleton();
               instance = temp
            }
         }
      }
      return instance;
   }
}
由于指令重排序问题,所以不可以直接写成下面这样:
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 Singleton instance = null;
   private Singleton() { }
   public static Singleton getInstance() {
      if(instance == null) {
         synchronzied(Singleton.class) {
            if(instance == null) {
               instance = new Singleton();
            }
         }
      }
      return instance;
   }
}

如果单体模式继续扩展为N元单体模式,那就是对象池模式了

最后编辑:
作者:IT江湖
我是IT江湖的创始人,也是现在主要的撰稿人!请大家多多支持!!!
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多