Go Pool

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

Pool is a concurrent-safe implementation of the object pool pattern. The pool pattern is a way to create and make available a fixed number of objects. It is commonly used to constrain creation of expensive resources, such as database connections, so that only a fixed number of them are ever created, but an indeterminate number of operations can still request access to them.

Instances are requested with Get(). When Get() is called, it will first check whether are any available instances within the pool, and if not, the New member variable, which is a constructor function, is used to create a new one.

When finished with the instance, the caller use Put() to place the instance back in the pool.

Example

pool := &sync.Pool{
	New: func() interface{} {
		fmt.Printf("creating new instance\n")
		return struct{}{}
	},
}

i := pool.Get()
i2 := pool.Get()
i3 := pool.Get()
pool.Put(i)
pool.Put(i2)
pool.Put(i3)