github.com/matrixorigin/matrixone@v1.2.0/pkg/common/reuse/sync_pool_based.go (about) 1 // Copyright 2023 Matrix Origin 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 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package reuse 16 17 import ( 18 "runtime" 19 "sync" 20 ) 21 22 type syncPoolBased[T ReusableObject] struct { 23 pool sync.Pool 24 reset func(*T) 25 opts *Options[T] 26 c *checker[T] 27 } 28 29 func newSyncPoolBased[T ReusableObject]( 30 new func() *T, 31 reset func(*T), 32 opts *Options[T]) Pool[T] { 33 opts.adjust() 34 c := newChecker[T](opts.enableChecker) 35 return &syncPoolBased[T]{ 36 pool: sync.Pool{ 37 New: func() any { 38 v := new() 39 c.created(v) 40 runtime.SetFinalizer( 41 v, 42 func(v *T) { 43 if opts.gcRecover != nil { 44 defer opts.gcRecover() 45 } 46 c.gc(v) 47 opts.release(v) 48 }) 49 return v 50 }, 51 }, 52 reset: reset, 53 opts: opts, 54 c: c, 55 } 56 } 57 58 func (p *syncPoolBased[T]) Alloc() *T { 59 v := p.pool.Get().(*T) 60 p.c.got(v) 61 return v 62 } 63 64 func (p *syncPoolBased[T]) Free(v *T) { 65 p.c.free(v) 66 p.reset(v) 67 p.pool.Put(v) 68 }