pool

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2025 License: MIT Imports: 5 Imported by: 2

README

⭐   the project to show your appreciation. :arrow_upper_right:

go-pool

A Generic sync.Pool

This package is a thin wrapper over the Pool provided by the sync package. The Pool is an essential package to obtain maximum performance. It does so by reducing memory allocations.

Extra Features

  • Invalidate an item from the Pool (so it never gets used again)
  • Set a maximum number of items for the Pool (Limit pool growth)
  • Return the number of items in the pool (idle and in-use)
  • Designed for concurrency
  • Fully Generic

When should I use a pool?

If you frequently allocate many objects of the same type and you want to save some memory allocation and garbage allocation overhead — @jrv

Read How did I improve latency by 700% using sync.Pool

Example

import "github.com/rocketlaunchr/go-pool"

type X struct {}

pool := pool.New(func() *X {
  return &X{}
}, 5) // maximum of 5 items can be borrowed at a time

borrowed := pool.Borrow()
defer borrowed.Return()

// Use item here or mark as invalid
x := borrowed.Item() // Use Item of type: *X
borrowed.MarkAsInvalid()

Other useful packages

  • awesome-svelte - Resources for killing react
  • dataframe-go - Statistics and data manipulation
  • dbq - Zero boilerplate database operations for Go
  • electron-alert - SweetAlert2 for Electron Applications
  • google-search - Scrape google search results
  • igo - A Go transpiler with cool new syntax such as fordefer (defer for for-loops)
  • mysql-go - Properly cancel slow MySQL queries
  • react - Build front end applications using Go
  • remember-go - Cache slow database queries
  • testing-go - Testing framework for unit testing
Logo Credits
  1. Renee French (gopher)
  2. Samuel Jirénius (illustration)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ItemWrap

type ItemWrap[T any] interface {
	// Return returns the item back to the pool.
	Return()

	// MarkAsInvalid marks the item as invalid (eg. unusable, unstable or broken) so
	// that after it gets returned to the pool, it is discarded. It will eventually
	// get garbage collected.
	MarkAsInvalid()

	// Item represents the unwrapped item borrowed from the pool.
	Item() T
}

ItemWrap wraps the item returned by the pool's factory.

type Options

type Options struct {
	// Initial creates an initial number of ready-to-use items in the pool.
	Initial uint32

	// Max represents the maximum number of items you can borrow at a time. This
	// prevents unbounded growth in the pool.
	//
	// Depending on the timing of Returns and Factory calls, the maximum number of
	// items in the pool can exceed Max by a small number for a short time.
	Max uint32

	// EnableCount, when set, enables the pool's Count function.
	//
	// NOTE: If you set this AND you need to set your own runtime Finalizer on the item,
	// wrap your item in another struct, with the Finalizer added to the inner item.
	EnableCount bool
}

Options configures the Pool struct.

type Pool

type Pool[T any] struct {
	// contains filtered or unexported fields
}

A Pool is a set of temporary objects that may be individually stored and retrieved.

Any item stored in the Pool may be removed automatically at any time without notification. If the Pool holds the only reference when this happens, the item might be deallocated.

A Pool is safe for use by multiple goroutines simultaneously.

Pool's purpose is to cache allocated but unused items for later reuse, relieving pressure on the garbage collector. That is, it makes it easy to build efficient, thread-safe free lists. However, it is not suitable for all free lists.

An appropriate use of a Pool is to manage a group of temporary items silently shared among and potentially reused by concurrent independent clients of a package. Pool provides a way to amortize allocation overhead across many clients.

The Pool scales under load and shrinks when quiescent.

On the other hand, a free list maintained as part of a short-lived object is not a suitable use for a Pool, since the overhead does not amortize well in that scenario. It is more efficient to have such objects implement their own free list.

A Pool must not be copied after first use.

func New

func New[T any](factory func() T, opts ...any) Pool[T]

New creates a new Pool.

factory specifies a function to generate a new item when Borrow is called. opts accepts either an int (representing the max) or an Options struct.

NOTE: factory should generally only return pointer types, since a pointer can be put into the return interface value without an allocation.

func (*Pool[T]) Borrow

func (p *Pool[T]) Borrow() ItemWrap[T]

Borrow obtains an item from the pool. If the Max option is set, then this function will block until an item is returned back into the pool.

After the item is no longer required, you must call Return on the item.

func (*Pool[T]) Count

func (p *Pool[T]) Count() uint32

Count returns approximately the number of items in the pool (idle). If you want an accurate number, call runtime.GC() twice before calling Count (not recommended).

NOTE: Count can exceed both the Initial and Max value by a small number for a short time.

func (*Pool[T]) OnLoan

func (p *Pool[T]) OnLoan() uint32

OnLoan returns how many items are in-use.

func (*Pool[T]) ReturnItem

func (p *Pool[T]) ReturnItem(x ItemWrap[T])

ReturnItem returns an item back to the pool. However, the recommended approach is to call Return on the ItemWrap.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL