@@ -13,6 +13,15 @@ import (
1313 "golang.org/x/sync/semaphore"
1414)
1515
16+ const (
17+ // BufferSize is the page size of the Global() pool
18+ BufferSize = 1024 * 1024
19+ // BufferCacheSize is the max number of buffers to keep in the cache for the Global() pool
20+ BufferCacheSize = 64
21+ // BufferCacheFlushTime is the max time to keep buffers in the Global() pool
22+ BufferCacheFlushTime = 5 * time .Second
23+ )
24+
1625// Pool of internal buffers
1726//
1827// We hold buffers in cache. Every time we Get or Put we update
@@ -67,6 +76,17 @@ func New(flushTime time.Duration, bufferSize, poolSize int, useMmap bool) *Pool
6776 return nil
6877 }
6978 }
79+
80+ // Initialise total memory limit if required
81+ totalMemoryInit .Do (func () {
82+ ci := fs .GetConfig (context .Background ())
83+
84+ // Set max buffer memory limiter
85+ if ci .MaxBufferMemory > 0 {
86+ totalMemory = semaphore .NewWeighted (int64 (ci .MaxBufferMemory ))
87+ }
88+ })
89+
7090 bp .timer = time .AfterFunc (flushTime , bp .flushAged )
7191 return bp
7292}
@@ -157,20 +177,10 @@ func (bp *Pool) updateMinFill() {
157177
158178// acquire mem bytes of memory
159179func (bp * Pool ) acquire (mem int64 ) error {
160- ctx := context .Background ()
161-
162- totalMemoryInit .Do (func () {
163- ci := fs .GetConfig (ctx )
164-
165- // Set max buffer memory limiter
166- if ci .MaxBufferMemory > 0 {
167- totalMemory = semaphore .NewWeighted (int64 (ci .MaxBufferMemory ))
168- }
169- })
170-
171180 if totalMemory == nil {
172181 return nil
173182 }
183+ ctx := context .Background ()
174184 return totalMemory .Acquire (ctx , mem )
175185}
176186
@@ -248,3 +258,17 @@ func (bp *Pool) Put(buf []byte) {
248258 bp .updateMinFill ()
249259 bp .kickFlusher ()
250260}
261+
262+ // bufferPool is a global pool of buffers
263+ var bufferPool * Pool
264+ var bufferPoolOnce sync.Once
265+
266+ // Global gets a global pool of BufferSize, BufferCacheSize, BufferCacheFlushTime.
267+ func Global () * Pool {
268+ bufferPoolOnce .Do (func () {
269+ // Initialise the buffer pool when used
270+ ci := fs .GetConfig (context .Background ())
271+ bufferPool = New (BufferCacheFlushTime , BufferSize , BufferCacheSize , ci .UseMmap )
272+ })
273+ return bufferPool
274+ }
0 commit comments