-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweakref_test.go
147 lines (130 loc) · 2.48 KB
/
weakref_test.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package weakref
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
)
var (
wg sync.WaitGroup
testingRace bool
finalizeCount int64
interfaceFinalizeCount int64
)
func makeRef() *WeakRef[[]int] {
a := make([]int, 1_000) // make a variable large enough to be garbage collected
p := &a
r := NewWeakRef(p)
return r
}
func testNewWeakRef(i int, t *testing.T) {
r2 := makeRef()
a := make([]int, 100)
a[0] = 123
p := &a
r := NewWeakRef(p)
if !IsAlive(r) {
t.Error(`early freed`)
}
if (*Get(r))[0] != 123 {
t.Fail()
}
_ = &a // keep a in memory til here
runtime.GC()
time.Sleep(time.Millisecond * 1)
runtime.GC()
time.Sleep(time.Millisecond * 1)
if IsAlive(r2) {
if !testingRace { // finalizer is called in a separated GoProc and may not finish yet in race condition
t.Error(`not freed`)
}
}
time.Sleep(time.Second)
if (*Get(r))[0] != 123 {
t.Fail()
}
runtime.KeepAlive(a)
runtime.GC()
time.Sleep(time.Millisecond * 10)
runtime.GC()
time.Sleep(time.Millisecond * 10)
p = Get(r)
isAlive := IsAlive(r)
if p == nil && isAlive {
t.Errorf(`wrong status %p, %t`, p, isAlive)
}
if p == nil {
atomic.AddInt64(&finalizeCount, 1)
}
// when p is not null isAlive may be false
if testingRace {
wg.Done()
}
}
func testNewFromSlice(i int, t *testing.T) {
a := []int{123, 222, 333}
r := NewWeakRef(&a[0])
if !IsAlive(r) {
t.Error(`early freed`)
}
if *Get(r) != 123 {
t.Fail()
}
a = append(a, make([]int, 255)...)
runtime.GC()
time.Sleep(time.Millisecond * 1)
runtime.GC()
time.Sleep(time.Millisecond * 1)
p := Get(r)
if p != nil {
if !IsAlive(r) {
t.Error(`wrong status`)
}
if *p != 123 {
t.Error(`bad pointer`)
}
} else {
if IsAlive(r) {
t.Error(`wrong status`)
}
}
// wrap a defer function to test if pointer is invalid
func() {
p := Get(r)
// if p != nil {
// if *p == a[0] {
// t.Error(`slice not moved`)
// }
// }
if p != nil {
if *p != a[0] {
t.Error(`bad pointer`)
}
}
}()
if testingRace {
wg.Done()
}
}
func TestOnce(t *testing.T) {
testNewWeakRef(-1, t)
testNewFromSlice(-1, t)
}
func TestRace(t *testing.T) {
testingRace = true
testCount := 500000
wg.Add(testCount * 2)
for i := 0; i < testCount; i++ {
ii := i
go testNewWeakRef(ii, t)
go testNewFromSlice(ii, t)
}
wg.Wait()
testingRace = false
fmt.Println(`run times: `, testCount, `, finalizeCount: `, finalizeCount)
if finalizeCount == 0 {
t.Error(`none finalized`)
}
}