Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 79c7328

Browse files
committed
add singleton readme in gof example
1 parent 88c2733 commit 79c7328

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

‎GOF/gof-example/src/main/java/com/ipipman/gof/example/singleton/GOF-Singleton单例模式.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,5 +75,37 @@ public class IdGenerator2 {
7575

7676

7777

78+
#### 3. 双重检测
79+
80+
饿汉式不支持延迟加载,懒汉式有性能问题,不支持高并发;
81+
82+
**双重检测** 兼顾了性能和延迟加载问题;
83+
84+
在实现方式中,只要 instance 被创建后,即便再调用 getInstance() 函数也不会再进入到加锁逻辑中了;
85+
86+
```java
87+
public class IdGenerator3 {
88+
private AtomicLong id = new AtomicLong(0);
89+
private static volatile IdGenerator3 instance;
90+
private IdGenerator3() {
91+
}
92+
public static IdGenerator3 getInstance() {
93+
if (instance == null) {
94+
synchronized (IdGenerator3.class) {
95+
if (instance == null) {
96+
instance = new IdGenerator3();
97+
}
98+
}
99+
}
100+
return instance;
101+
}
102+
public Long getId() {
103+
return id.incrementAndGet();
104+
}
105+
}
106+
```
107+
108+
109+
78110

79111

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.ipipman.gof.example.singleton;
2+
3+
import java.util.concurrent.atomic.AtomicLong;
4+
5+
// 3.双重检测
6+
// 饿汉式不支持延迟加载,懒汉式有性能问题,不支持高并发;
7+
// 双重检测 兼顾了性能和延迟加载问题;
8+
// 在实现方式中,只要 instance 被创建后,即便再调用 getInstance() 函数也不会再进入到加锁逻辑中了;
9+
10+
public class IdGenerator3 {
11+
private AtomicLong id = new AtomicLong(0);
12+
private static volatile IdGenerator3 instance;
13+
private IdGenerator3() {
14+
}
15+
public static IdGenerator3 getInstance() {
16+
if (instance == null) {
17+
synchronized (IdGenerator3.class) {
18+
if (instance == null) {
19+
instance = new IdGenerator3();
20+
}
21+
}
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+
IdGenerator3 idGenerator3 = IdGenerator3.getInstance();
33+
System.out.println(idGenerator3.getId());
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /