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