pooling
API
pooling
packageAPI reference for the pooling
package.
Imports
(2)
S
struct
Pool
Pool is a generic object pool with optional max size and finalizer.
core/pooling/pool.go:8-14
type Pool struct
Fields
| Name | Type | Description |
|---|---|---|
| pool | sync.Pool | |
| factory | func() T | |
| items | chan T | |
| maxSize | int | |
| finalizer | func(T) |
T
type
Option
Option configures a Pool.
core/pooling/pool.go:17-17
type Option func(*Pool[T])
F
function
New
New creates a new Pool using factory to create items.
Parameters
factory
func() T
opts
...Option[T]
Returns
*Pool[T]
core/pooling/pool.go:20-30
func New[T any](factory func() T, opts ...Option[T]) *Pool[T]
{
p := &Pool[T]{factory: factory}
p.pool = sync.Pool{New: func() any { return factory() }}
for _, opt := range opts {
opt(p)
}
if p.maxSize > 0 {
p.items = make(chan T, p.maxSize)
}
return p
}
F
function
WithMaxSize
WithMaxSize limits the number of retained items.
Parameters
n
int
Returns
Option[T]
core/pooling/pool.go:33-35
func WithMaxSize[T any](n int) Option[T]
{
return func(p *Pool[T]) { p.maxSize = n }
}
F
function
WithFinalizer
WithFinalizer sets a cleanup function called before items are returned.
Parameters
fn
func(T)
Returns
Option[T]
core/pooling/pool.go:38-40
func WithFinalizer[T any](fn func(T)) Option[T]
{
return func(p *Pool[T]) { p.finalizer = fn }
}
F
function
TestPoolReusesReturnedItem
Parameters
t
core/pooling/pool_test.go:5-18
func TestPoolReusesReturnedItem(t *testing.T)
{
next := 0
p := New(func() int {
next++
return next
}, WithMaxSize[int](1))
item := p.Get()
p.Put(item)
if got := p.Get(); got != item {
t.Fatalf("Get() = %d, want %d", got, item)
}
}
F
function
TestPoolMaxSizeLimitsRetainedItems
Parameters
t
core/pooling/pool_test.go:20-36
func TestPoolMaxSizeLimitsRetainedItems(t *testing.T)
{
next := 0
p := New(func() int {
next++
return next
}, WithMaxSize[int](1))
p.Put(10)
p.Put(20)
if got := p.Get(); got != 10 {
t.Fatalf("Get() = %d, want first retained item", got)
}
if got := p.Get(); got != 1 {
t.Fatalf("Get() = %d, want new factory item", got)
}
}
F
function
TestPoolFinalizerRunsBeforeRetain
Parameters
t
core/pooling/pool_test.go:38-50
func TestPoolFinalizerRunsBeforeRetain(t *testing.T)
{
p := New(func() []int { return []int{1, 2} }, WithFinalizer(func(v []int) {
v[0] = 9
}), WithMaxSize[[]int](1))
item := p.Get()
p.Put(item)
got := p.Get()
if got[0] != 9 {
t.Fatalf("Get()[0] = %d, want finalizer mutation", got[0])
}
}