Skip to content

Commit 7c71074

Browse files
committed
20220420
1 parent 126adf0 commit 7c71074

File tree

2 files changed

+100
-1
lines changed

2 files changed

+100
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ ps:白天上班,晚上更新,尽量日更,比心
6969

7070
[第30章 对象池](https://github.com/java-aodeng/golang-examples/blob/master/go-30/obj_pool_test.go)
7171

72-
第31章 sync.pool对象缓存
72+
[第31章 sync.pool对象缓存](https://github.com/java-aodeng/golang-examples/blob/master/go-31/sync_pool_test.go)
7373

7474
第32章 单元测试
7575

go-31/sync_pool_test.go

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package go_31
2+
3+
import (
4+
"fmt"
5+
"runtime"
6+
"sync"
7+
"testing"
8+
)
9+
10+
/*
11+
sync.pool对象缓存
12+
13+
sync.Pool对象获取
14+
- 尝试从私有对象获取
15+
- 私有对象不存在,尝试从当前Processor的共享池获取
16+
- 如果当前Processor共享池是空的,那么就尝试去其他Processor的共享池获取
17+
- 如果所有池都是空的,最后就用用户指定的new函数产生一个新的对象返回
18+
19+
sync.Pool对象的生命周期
20+
- GC会清楚sync.pool缓存的对象
21+
- 对象的缓存有效期为下一次GC之前
22+
23+
sync.Pool总结
24+
- 使用与通过复用,降低复杂对象的创建和GC代价
25+
- 协程安全,会有锁的开销
26+
- 生命周期受GC影响,不适合于做连接池等,需要自己管理生命周期的资源池化
27+
*/
28+
29+
func TestSyncPool(t *testing.T) {
30+
pool := &sync.Pool{
31+
New: func() interface{} {
32+
fmt.Println("创建一个对象.")
33+
return 100
34+
},
35+
}
36+
v := pool.Get().(int)
37+
fmt.Println("得到的对象", v)
38+
//手动添加值
39+
pool.Put(1)
40+
//GC会清除sync.pool中缓存的对象
41+
runtime.GC()
42+
v1, _ := pool.Get().(int)
43+
fmt.Println("v1=", v1)
44+
}
45+
46+
/*TestSyncPool运行结果 可以看到GC之前put的1没有输出,被清除了
47+
=== RUN TestSyncPool
48+
创建一个对象.
49+
得到的对象 100
50+
创建一个对象.
51+
v1= 100
52+
--- PASS: TestSyncPool (0.00s)
53+
PASS
54+
*/
55+
56+
func TestSyncPoolInMultiGroutine(t *testing.T) {
57+
pool := &sync.Pool{
58+
New: func() interface{} {
59+
fmt.Println("创建一个对象.")
60+
return 10
61+
},
62+
}
63+
64+
pool.Put(100)
65+
pool.Put(100)
66+
pool.Put(100)
67+
68+
var wg sync.WaitGroup
69+
for i := 0; i < 10; i++ {
70+
wg.Add(1)
71+
go func(id int) {
72+
fmt.Println(pool.Get())
73+
wg.Done()
74+
}(i)
75+
}
76+
wg.Wait()
77+
}
78+
79+
/*
80+
运行结果 可以看到10次里面三次都是取的100,7次是创建的10
81+
=== RUN TestSyncPoolInMultiGroutine
82+
100
83+
创建一个对象.
84+
10
85+
100
86+
创建一个对象.
87+
10
88+
创建一个对象.
89+
创建一个对象.
90+
10
91+
创建一个对象.
92+
创建一个对象.
93+
10
94+
创建一个对象.
95+
10
96+
100
97+
10
98+
10
99+
*/

0 commit comments

Comments
 (0)