1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Pool is no-op under race detector, so all these tests do not work.
19 func TestPool(t
*testing
.T
) {
20 // disable GC so we can control when it happens.
21 defer debug
.SetGCPercent(debug
.SetGCPercent(-1))
24 t
.Fatal("expected empty")
28 if g
:= p
.Get(); g
!= "a" {
29 t
.Fatalf("got %#v; want a", g
)
31 if g
:= p
.Get(); g
!= "b" {
32 t
.Fatalf("got %#v; want b", g
)
34 if g
:= p
.Get(); g
!= nil {
35 t
.Fatalf("got %#v; want nil", g
)
39 debug
.SetGCPercent(100) // to allow following GC to actually run
41 if g
:= p
.Get(); g
!= nil {
42 t
.Fatalf("got %#v; want nil after GC", g
)
46 func TestPoolNew(t
*testing
.T
) {
47 // disable GC so we can control when it happens.
48 defer debug
.SetGCPercent(debug
.SetGCPercent(-1))
52 New
: func() interface{} {
57 if v
:= p
.Get(); v
!= 1 {
58 t
.Fatalf("got %v; want 1", v
)
60 if v
:= p
.Get(); v
!= 2 {
61 t
.Fatalf("got %v; want 2", v
)
64 if v
:= p
.Get(); v
!= 42 {
65 t
.Fatalf("got %v; want 42", v
)
67 if v
:= p
.Get(); v
!= 3 {
68 t
.Fatalf("got %v; want 3", v
)
72 // Test that Pool does not hold pointers to previously cached
74 func TestPoolGC(t
*testing
.T
) {
78 for i
:= 0; i
< N
; i
++ {
80 runtime
.SetFinalizer(v
, func(vv
*string) {
81 atomic
.AddUint32(&fin
, 1)
85 for i
:= 0; i
< N
; i
++ {
88 for i
:= 0; i
< 5; i
++ {
90 time
.Sleep(time
.Duration(i
*100+10) * time
.Millisecond
)
91 // 1 pointer can remain on stack or elsewhere
92 if atomic
.LoadUint32(&fin
) >= N
-1 {
96 // gccgo has a less precise heap.
97 if runtime
.Compiler
== "gccgo" && atomic
.LoadUint32(&fin
) >= N
-5 {
101 t
.Fatalf("only %v out of %v resources are finalized",
102 atomic
.LoadUint32(&fin
), N
)
105 func TestPoolStress(t
*testing
.T
) {
112 done
:= make(chan bool)
113 for i
:= 0; i
< P
; i
++ {
115 var v
interface{} = 0
116 for j
:= 0; j
< N
; j
++ {
122 if v
!= nil && v
.(int) != 0 {
123 t
.Fatalf("expect 0, got %v", v
)
129 for i
:= 0; i
< P
; i
++ {
134 func BenchmarkPool(b
*testing
.B
) {
136 b
.RunParallel(func(pb
*testing
.PB
) {
144 func BenchmarkPoolOverlflow(b
*testing
.B
) {
146 b
.RunParallel(func(pb
*testing
.PB
) {
148 for b
:= 0; b
< 100; b
++ {
151 for b
:= 0; b
< 100; b
++ {