Go Pool: Difference between revisions
Jump to navigation
Jump to search
Line 2: | Line 2: | ||
* [[Go_Package_sync#Pool|The <tt>sync</tt> Package]] | * [[Go_Package_sync#Pool|The <tt>sync</tt> Package]] | ||
=Overview= | =Overview= | ||
<code>Pool</code> is a concurrent-safe implementation of the object pool pattern. | <code>Pool</code> 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 <code>Get()</code>. When <code>Get()</code> is called, it will first check whether are any available instances within the pool, and if not, the <code>New</code> member variable, which is a constructor function, is used to create a new one. | |||
When finished with the instance, the caller use <code>Put()</code> to place the instance back in the pool. | |||
=Example= | |||
<syntaxhighlight lang='go'> | |||
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) | |||
</syntaxhighlight> |
Latest revision as of 00:13, 21 January 2024
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)