1
// Copyright 2013 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
11
// A Pool is a set of temporary objects that may be individually saved and
14
// Any item stored in the Pool may be removed automatically at any time without
15
// notification. If the Pool holds the only reference when this happens, the
16
// item might be deallocated.
18
// A Pool is safe for use by multiple goroutines simultaneously.
20
// Pool's purpose is to cache allocated but unused items for later reuse,
21
// relieving pressure on the garbage collector. That is, it makes it easy to
22
// build efficient, thread-safe free lists. However, it is not suitable for all
25
// An appropriate use of a Pool is to manage a group of temporary items
26
// silently shared among and potentially reused by concurrent independent
27
// clients of a package. Pool provides a way to amortize allocation overhead
28
// across many clients.
30
// An example of good use of a Pool is in the fmt package, which maintains a
31
// dynamically-sized store of temporary output buffers. The store scales under
32
// load (when many goroutines are actively printing) and shrinks when
35
// On the other hand, a free list maintained as part of a short-lived object is
36
// not a suitable use for a Pool, since the overhead does not amortize well in
37
// that scenario. It is more efficient to have such objects implement their own
44
// New optionally specifies a function to generate
45
// a value when Get would otherwise return nil.
46
// It may not be changed concurrently with calls to Get.
47
New func() interface{}
50
// Put adds x to the pool.
51
func (p *Pool) Put(x interface{}) {
53
p.values = append(p.values, x)
57
// Get selects an arbitrary item from the Pool, removes it from the
58
// Pool, and returns it to the caller.
59
// Get may choose to ignore the pool and treat it as empty.
60
// Callers should not assume any relation between values passed to Put and
61
// the values returned by Get.
63
// If Get would otherwise return nil and p.New is non-nil, Get returns
64
// the result of calling p.New.
65
func (p *Pool) Get() interface{} {
67
if n := len(p.values); n > 0 {
69
p.values = p.values[0 : n-1]