/ pool / read_buffer.go
read_buffer.go
 1  package pool
 2  
 3  import (
 4  	"time"
 5  
 6  	"github.com/lightningnetwork/lnd/buffer"
 7  )
 8  
 9  const (
10  	// DefaultReadBufferGCInterval is the default interval that a Read will
11  	// perform a sweep to see which expired buffer.Reads can be released to
12  	// the runtime.
13  	DefaultReadBufferGCInterval = 15 * time.Second
14  
15  	// DefaultReadBufferExpiryInterval is the default, minimum interval that
16  	// must elapse before a Read will release a buffer.Read. The maximum
17  	// time before the buffer can be released is equal to the expiry
18  	// interval plus the gc interval.
19  	DefaultReadBufferExpiryInterval = 30 * time.Second
20  )
21  
22  // ReadBuffer is a pool of buffer.Read items, that dynamically allocates and
23  // reclaims buffers in response to load.
24  type ReadBuffer struct {
25  	pool *Recycle
26  }
27  
28  // NewReadBuffer returns a freshly instantiated ReadBuffer, using the given
29  // gcInterval and expiryInterval.
30  func NewReadBuffer(gcInterval, expiryInterval time.Duration) *ReadBuffer {
31  	return &ReadBuffer{
32  		pool: NewRecycle(
33  			func() interface{} { return new(buffer.Read) },
34  			100, gcInterval, expiryInterval,
35  		),
36  	}
37  }
38  
39  // Take returns a fresh buffer.Read to the caller.
40  func (p *ReadBuffer) Take() *buffer.Read {
41  	return p.pool.Take().(*buffer.Read)
42  }
43  
44  // Return returns the buffer.Read to the pool, so that it can be cycled or
45  // released.
46  func (p *ReadBuffer) Return(buf *buffer.Read) {
47  	p.pool.Return(buf)
48  }