-
Notifications
You must be signed in to change notification settings - Fork 2
/
tpool.go
44 lines (37 loc) · 815 Bytes
/
tpool.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
package gojsx
import (
"context"
pool "github.com/jolestar/go-commons-pool/v2"
)
type tPool[T any] struct {
op *pool.ObjectPool
}
func newTPool[T any](maxTotal int, fun func() T) *tPool[T] {
factory := pool.NewPooledObjectFactorySimple(
func(context.Context) (interface{}, error) {
return fun(), nil
})
ctx := context.Background()
p := pool.NewObjectPool(ctx, factory, &pool.ObjectPoolConfig{
MaxIdle: -1,
MaxTotal: maxTotal,
BlockWhenExhausted: true,
})
return &tPool[T]{
op: p,
}
}
func (p *tPool[T]) Get() (t T, err error) {
o, err := p.op.BorrowObject(context.Background())
if err != nil {
return
}
return o.(T), nil
}
func (p *tPool[T]) Put(t T) error {
err := p.op.ReturnObject(context.Background(), t)
if err != nil {
return err
}
return nil
}