github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/kv/bufpool.go (about) 1 // Copyright 2015 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package kv 15 16 import ( 17 "sync" 18 19 "github.com/insionng/yougam/libraries/ngaut/log" 20 ) 21 22 // A cache holds a set of reusable objects. 23 // The slice is a stack (LIFO). 24 // If more are needed, the cache creates them by calling new. 25 type cache struct { 26 mu sync.Mutex 27 name string 28 saved []MemBuffer 29 // factory 30 fact func() MemBuffer 31 } 32 33 func (c *cache) put(x MemBuffer) { 34 c.mu.Lock() 35 if len(c.saved) < cap(c.saved) { 36 c.saved = append(c.saved, x) 37 } else { 38 log.Warnf("%s is full, size: %d, you may need to increase pool size", c.name, len(c.saved)) 39 } 40 c.mu.Unlock() 41 } 42 43 func (c *cache) get() MemBuffer { 44 c.mu.Lock() 45 n := len(c.saved) 46 if n == 0 { 47 c.mu.Unlock() 48 return c.fact() 49 } 50 x := c.saved[n-1] 51 c.saved = c.saved[0 : n-1] 52 c.mu.Unlock() 53 return x 54 } 55 56 func newCache(name string, cap int, fact func() MemBuffer) *cache { 57 return &cache{name: name, saved: make([]MemBuffer, 0, cap), fact: fact} 58 }