-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool.go
51 lines (42 loc) · 804 Bytes
/
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
package jsn_net
import (
"fmt"
"reflect"
"sync"
"sync/atomic"
)
type SyncPool[B any] struct {
data *sync.Pool
debug int64
}
func (s *SyncPool[B]) Init() error {
if nil == s.convert(new(B)) {
return fmt.Errorf("%v need release interface", reflect.ValueOf(new(B)).Type().String())
}
s.data = &sync.Pool{New: func() any {
return new(B)
}}
return nil
}
func (s *SyncPool[B]) Get() *B {
atomic.AddInt64(&s.debug, 1)
return s.data.Get().(*B)
}
type poolRelease interface {
Release()
}
func (s *SyncPool[B]) Put(b *B) {
if nil == b {
return
}
poolRelease.Release(s.convert(b))
s.data.Put(b)
atomic.AddInt64(&s.debug, -1)
}
func (s *SyncPool[B]) convert(b *B) poolRelease {
ret, _ := (any(b)).(poolRelease)
return ret
}
func (s *SyncPool[B]) Debug() int64 {
return s.debug
}