Created
March 13, 2022 21:42
-
-
Save noclue/055ccbaf51940413732b1ea903c189e7 to your computer and use it in GitHub Desktop.
Generic Pool implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package pkg | |
| import "sync" | |
| // Pool is a generic interface for managing objects to reused in many go | |
| // routines. It resembles the sync.Pool built in type with added type safety. | |
| type Pool[T any] interface { | |
| Get() T | |
| Put(T) | |
| } | |
| type poolImpl[T any] struct { | |
| pool sync.Pool | |
| } | |
| var _ Pool[int] = &poolImpl[int]{} | |
| // NewPool allocates a new Pool instance. | |
| func NewPool[T any](itemFactory func() T) Pool[T] { | |
| factory := func() any { return itemFactory() } | |
| return &poolImpl[T]{ | |
| pool: sync.Pool{ | |
| New: factory, | |
| }, | |
| } | |
| } | |
| // Get retrieves an instance from a pool of objects. The instance must be Put | |
| // back in the pool after use. | |
| // | |
| // See sync.Pool for more info. | |
| func (p *poolImpl[T]) Get() T { | |
| return p.pool.Get().(T) | |
| } | |
| // Put returns an instance to the Pool. | |
| // | |
| // See sync.Pool for more info. | |
| func (p *poolImpl[T]) Put(v T) { | |
| p.pool.Put(v) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment