Skip to content

Commit

Permalink
limit bytes pool object size (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexStocks committed Sep 12, 2021
1 parent dbf1d9e commit b640a57
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

*.idea
*.iml
*.vscode
target/
classes

Expand Down
32 changes: 30 additions & 2 deletions bytes/bytes_buffer_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,50 @@ import (
"sync"
)

var defaultPool *ObjectPool
import (
uatomic "go.uber.org/atomic"
)

var (
poolObjectNumber uatomic.Int64
defaultPool *ObjectPool

minBufCap = 512
maxBufCap = 20 * 1024
maxPoolObjectNum = int64(4000)
)

func init() {
defaultPool = NewObjectPool(func() PoolObject {
return new(bytes.Buffer)
})
poolObjectNumber.Store(0)
}

// GetBytesBuffer returns bytes.Buffer from pool
func GetBytesBuffer() *bytes.Buffer {
return defaultPool.Get().(*bytes.Buffer)
buf := defaultPool.Get().(*bytes.Buffer)
bufCap := buf.Cap()
if bufCap >= minBufCap && bufCap <= maxBufCap && poolObjectNumber.Load() > 0 {
poolObjectNumber.Dec()
}

return buf
}

// PutIoBuffer returns IoBuffer to pool
func PutBytesBuffer(buf *bytes.Buffer) {
if poolObjectNumber.Load() > maxPoolObjectNum {
return
}

bufCap := buf.Cap()
if bufCap < minBufCap || bufCap > maxBufCap {
return
}

defaultPool.Put(buf)
poolObjectNumber.Add(1)
}

// Pool object
Expand Down

0 comments on commit b640a57

Please sign in to comment.