Skip to content

Instantly share code, notes, and snippets.

@ozkansen
Created April 19, 2023 09:00
Show Gist options
  • Save ozkansen/669e9479995fb6d95704d11e02bcb67b to your computer and use it in GitHub Desktop.
Save ozkansen/669e9479995fb6d95704d11e02bcb67b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
type ObjectPool[T any] struct {
pool sync.Pool
stats struct {
create *int64
allocate int64
access int64
}
}
func (o *ObjectPool[T]) Get() T {
atomic.AddInt64(&o.stats.allocate, 1)
atomic.AddInt64(&o.stats.access, 1)
t, _ := o.pool.Get().(T)
return t
}
func (o *ObjectPool[T]) Put(x T) {
o.pool.Put(x)
atomic.AddInt64(&o.stats.allocate, -1)
}
func (o *ObjectPool[T]) Stats() {
fmt.Printf("create:%d, allocate:%d, access:%d\n", *o.stats.create, o.stats.allocate, o.stats.access)
fmt.Printf("%+v", o.pool)
}
func NewObjectPool() *ObjectPool[*Deneme] {
var create int64
return &ObjectPool[*Deneme]{
pool: sync.Pool{
New: func() any {
atomic.AddInt64(&create, 1)
deneme := Deneme{}
deneme.Reset()
return &deneme
},
},
stats: struct {
create *int64
allocate int64
access int64
}{
create: &create,
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment