-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
58 lines (45 loc) · 1.09 KB
/
pool.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
package factory
import (
"reflect"
"sync"
)
var _poolCache = map[reflect.Type]*sync.Pool{}
var _poolCacheLock = &sync.RWMutex{}
func getPoolByType(vt reflect.Type) *sync.Pool {
_poolCacheLock.RLock()
pool, ok := _poolCache[vt]
_poolCacheLock.RUnlock()
if !ok {
pool = &sync.Pool{
New: func() interface{} {
return initWithOptionTimeout(reflect.New(vt).Interface(), newDefaultOption, Opts.Timeout)
},
}
_poolCacheLock.Lock()
_poolCache[vt] = pool
_poolCacheLock.Unlock()
}
return pool
}
func Get[T any]() *T {
return getPoolByType(reflect.TypeOf((*T)(nil)).Elem()).Get().(*T)
}
func Put[T any](t *T) {
if t == nil {
return
}
getPoolByType(reflect.TypeOf((*T)(nil)).Elem()).Put(t)
}
func SetPoolInit[T any](option *Option) {
setPoolInitWithType(reflect.TypeOf((*T)(nil)).Elem(), option)
}
func setPoolInitWithType(vt reflect.Type, option *Option) {
pool := &sync.Pool{
New: func() interface{} {
return initWithOptionTimeout(reflect.New(vt).Interface(), option, Opts.Timeout)
},
}
_poolCacheLock.Lock()
defer _poolCacheLock.Unlock()
_poolCache[vt] = pool
}