github.com/decred/dcrlnd@v0.7.6/pool/recycle.go (about) 1 package pool 2 3 import ( 4 "time" 5 6 "github.com/decred/dcrlnd/queue" 7 ) 8 9 // Recycler is an interface that allows an object to be reclaimed without 10 // needing to be returned to the runtime. 11 type Recycler interface { 12 // Recycle resets the object to its default state. 13 Recycle() 14 } 15 16 // Recycle is a generic queue for recycling objects implementing the Recycler 17 // interface. It is backed by an underlying queue.GCQueue, and invokes the 18 // Recycle method on returned objects before returning them to the queue. 19 type Recycle struct { 20 queue *queue.GCQueue 21 } 22 23 // NewRecycle initializes a fresh Recycle instance. 24 func NewRecycle(newItem func() interface{}, returnQueueSize int, 25 gcInterval, expiryInterval time.Duration) *Recycle { 26 27 return &Recycle{ 28 queue: queue.NewGCQueue( 29 newItem, returnQueueSize, 30 gcInterval, expiryInterval, 31 ), 32 } 33 } 34 35 // Take returns an element from the pool. 36 func (r *Recycle) Take() interface{} { 37 return r.queue.Take() 38 } 39 40 // Return returns an item implementing the Recycler interface to the pool. The 41 // Recycle method is invoked before returning the item to improve performance 42 // and utilization under load. 43 func (r *Recycle) Return(item Recycler) { 44 // Recycle the item to ensure that a dirty instance is never offered 45 // from Take. The call is done here so that the CPU cycles spent 46 // clearing the buffer are owned by the caller, and not by the queue 47 // itself. This makes the queue more likely to be available to deliver 48 // items in the free list. 49 item.Recycle() 50 51 r.queue.Return(item) 52 }