话不多说上代码!其中main函数是模仿多线程访问单例,打印对象的hashCode值来查看多线程环境下拿到的实例是不是同一个。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package com.kali.jvm.singleton; public class V1Singleton { private static final V1Singleton INSTANCE = new V1Singleton(); private V1Singleton(){} public static V1Singleton getInstance(){ return INSTANCE; } public static void main(String[] args) { for (int i = 0; i < 10000; i++) { new Thread(() ->{ System.out.println(getInstance().hashCode()); }).start(); } } }
这是最简单的单例模式。
以下是DCL单例模式形成的过程:
一、多线程情况下加锁:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24package com.kali.jvm.singleton; public class V3Singleton { private static V3Singleton SINGLETON_INSTANCE; private V3Singleton(){} public static synchronized V3Singleton getInstance(){ if(SINGLETON_INSTANCE == null){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } SINGLETON_INSTANCE = new V3Singleton(); } return SINGLETON_INSTANCE; } public static void main(String[] args) { for (int i = 0; i < 10000; i++) { new Thread(() ->{ System.out.println(getInstance().hashCode()); }).start(); } } }
二、为了提高效率缩小锁的粒度:
复制代码
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
26package com.kali.jvm.singleton; public class V3Singleton { private static V3Singleton SINGLETON_INSTANCE; private V3Singleton(){} public static V3Singleton getInstance(){ if(SINGLETON_INSTANCE == null){ synchronized (V3Singleton.class){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } SINGLETON_INSTANCE = new V3Singleton(); } } return SINGLETON_INSTANCE; } public static void main(String[] args) { for (int i = 0; i < 10000; i++) { new Thread(() ->{ System.out.println(getInstance().hashCode()); }).start(); } } }
在JAVA中多线程并发环境下会出错的数据被称为竞态条件。
三、上面缩小锁粒度后的程序在并发情况下还是会出现问题,当一个线程判断SINGLETON_INSTANCE为null时,恰好时间片到了,下一个线程来了之后判断为null,拿到了锁然后返回实例对象,释放锁,这时候第一个线程继续执行,因为已经判断了SINGLETON_INSTANCE为null,然后拿锁执行,又产生了一个实例。保证不了单例。所以加了双重所检查机制。
复制代码
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
32package com.kali.jvm.singleton; /** * DCL双重检查锁 * DCL单例到底需要加volatile? */ public class V2Singleton { private static V2Singleton SINGLETON_INSTANCE; private V2Singleton(){} public static V2Singleton getInstance(){ if(SINGLETON_INSTANCE == null){ synchronized (V2Singleton.class){ if(SINGLETON_INSTANCE == null){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } SINGLETON_INSTANCE = new V2Singleton(); } } } return SINGLETON_INSTANCE; } public static void main(String[] args) { for (int i = 0; i < 10000; i++) { new Thread(() ->{ System.out.println(getInstance().hashCode()); }).start(); } } }
最后
以上就是高贵唇彩最近收集整理的关于Java单例之DCL双重检查锁的全部内容,更多相关Java单例之DCL双重检查锁内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复