sequence

This paper mainly studies ObjectPool of GOst

ObjectPool

gost/bytes/bytes_buffer_pool.go

// Pool is bytes.Buffer Pool
type ObjectPool struct {
	New  New
	pool sync.Pool
}

func NewObjectPool(n New) *ObjectPool {
	return &ObjectPool{New: n}
}

// take returns *bytes.Buffer from Pool
func (p *ObjectPool) Get() PoolObject {
	v := p.pool.Get()
	if v == nil {
		return p.New()
	}

	return v.(PoolObject)
}

// give returns *byes.Buffer to Pool
func (p *ObjectPool) Put(o PoolObject) {
	o.Reset()
	p.pool.Put(o)
}

// Pool object
type PoolObject interface {
	Reset()
}

type New func() PoolObject
Copy the code

ObjectPool defines the New and sync.Pool attributes, which provide the Get and Put methods, as well as the NewObjectPool project methods. New is a func that returns PoolObject; The PoolObject interface defines the Reset method

defaultPool

gost/bytes/bytes_buffer_pool.go

var (
	defaultPool *ObjectPool
)

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

// GetBytesBuffer returns bytes.Buffer from pool
func GetBytesBuffer() *bytes.Buffer {
	return defaultPool.Get().(*bytes.Buffer)
}

// PutIoBuffer returns IoBuffer to pool
func PutBytesBuffer(buf *bytes.Buffer) {
	defaultPool.Put(buf)
}
Copy the code

DefaultPool Creates an ObjectPool whose Reset method is new(bytes.buffer) and whose GetBytesBuffer converts defaultPool.get () to the * bytes.buffer type

The instance

gost/bytes/bytes_buffer_pool_test.go

func TestBytesBufferPool(t *testing.T) { buf := GetBytesBuffer() bytes := []byte{0x00, 0x01, 0x02, 0x03, 0x04} buf.Write(bytes) if buf.Len() ! = len(bytes) { t.Error("iobuffer len not match write bytes' size") } PutBytesBuffer(buf) //buf2 := GetBytesBuffer() // HTTP: / / https://go-review.googlesource.com/c/go/+/162919/ / / before go 1.13, Sync. Pool just reserves some objs before every GC and will be cleanup by gc. // After Go 1.13, maybe there are many reserved objs after gc. //if buf ! = buf2 { // t.Errorf("buf pointer %p ! = buf2 pointer %p", buf, buf2) //} }Copy the code

Here we show a GetBytesBuffer to get buF and PutBytesBuffer to return BUF

summary

Gost ObjectPool defines the New and sync.Pool attributes, which provide the Get and Put methods, as well as the NewObjectPool project methods. New is a func that returns PoolObject; The PoolObject interface defines the Reset method.

doc

  • gost