File tree Expand file tree Collapse file tree 3 files changed +80
-1
lines changed
GOF/gof-example/src/main/java/com/ipipman/gof/example/singleton Expand file tree Collapse file tree 3 files changed +80
-1
lines changed Original file line number Diff line number Diff line change 3030
3131不过,这样实现方式不支持延迟加载,初始化时可能会耗性能;
3232
33+ ``` java
34+ public class IdGenerator1 {
35+ private AtomicLong id = new AtomicLong (0 );
36+ private static final IdGenerator1 instance = new IdGenerator1 ();
37+ private IdGenerator1 () {
38+ }
39+ public static IdGenerator1 getInstance () {
40+ return instance;
41+ }
42+ public Long getId (){
43+ return id. incrementAndGet();
44+ }
45+ }
46+ ```
47+
48+
49+
50+ #### 2. 懒汉试
51+
52+ 有饿汉式就有懒汉式;
53+
54+ 懒汉式对于饿汉式的优势在于它支持延迟加载,不影响初始化性能;
55+
56+ 不过懒汉试缺点也很明显,我们给 getInstance() 加了一个 synchronized 锁,导致这个方法并发度很低,性能非常差;
57+
58+ ``` java
59+ public class IdGenerator2 {
60+ private AtomicLong id = new AtomicLong (0 );
61+ private static IdGenerator2 instance;
62+ private IdGenerator2 () {
63+ }
64+ public static synchronized IdGenerator2 getInstance () {
65+ if (instance == null ) {
66+ instance = new IdGenerator2 ();
67+ }
68+ return instance;
69+ }
70+ public Long getId () {
71+ return id. incrementAndGet();
72+ }
73+ }
74+ ```
75+
3376
3477
3578
Original file line number Diff line number Diff line change 11package com .ipipman .gof .example .singleton ;
22
3- // 饿汉式
3+ // 1. 饿汉式
44// 饿汉式的实现比较简单,在类加载的时候,instance 静态实例已经创建并初始化好了,所以 instance 实例是线程安全的;
55// 不过,这样实现方式不支持延迟加载,初始化时可能会耗性能;
66
Original file line number Diff line number Diff line change 1+ package com .ipipman .gof .example .singleton ;
2+
3+ // 2.懒汉试
4+ // 有饿汉式就有懒汉式;
5+ // 懒汉式对于饿汉式的优势在于它支持延迟加载,不影响初始化性能;
6+ // 不过懒汉试缺点也很明显,我们给 getInstance() 加了一个 synchronized 锁,导致这个方法并发度很低,性能非常差;
7+
8+ import java .util .concurrent .atomic .AtomicLong ;
9+
10+ public class IdGenerator2 {
11+
12+ private AtomicLong id = new AtomicLong (0 );
13+ private static IdGenerator2 instance ;
14+
15+ private IdGenerator2 () {
16+
17+ }
18+
19+ public static synchronized IdGenerator2 getInstance () {
20+ if (instance == null ) {
21+ instance = new IdGenerator2 ();
22+ }
23+ return instance ;
24+ }
25+
26+ public Long getId () {
27+ return id .incrementAndGet ();
28+ }
29+
30+ // TODO Testing...
31+ public static void main (String [] args ) {
32+ IdGenerator2 idGenerator2 = IdGenerator2 .getInstance ();
33+ System .out .println (idGenerator2 .getId ());
34+ }
35+
36+ }
You can’t perform that action at this time.
0 commit comments