github.com/bytedance/gopkg@v0.0.0-20240514070511-01b2cbcf35e1/lang/syncx/pool_race.go (about) 1 // Copyright 2021 ByteDance 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 // 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 //go:build race 16 // +build race 17 18 package syncx 19 20 import ( 21 "sync" 22 ) 23 24 type Pool struct { 25 p sync.Pool 26 once sync.Once 27 // New optionally specifies a function to generate 28 // a value when Get would otherwise return nil. 29 // It may not be changed concurrently with calls to Get. 30 New func() interface{} 31 // NoGC any objects in this Pool. 32 NoGC bool 33 } 34 35 func (p *Pool) init() { 36 p.once.Do(func() { 37 p.p = sync.Pool{ 38 New: p.New, 39 } 40 }) 41 } 42 43 // Put adds x to the pool. 44 func (p *Pool) Put(x interface{}) { 45 p.init() 46 p.p.Put(x) 47 } 48 49 // Get selects an arbitrary item from the Pool, removes it from the 50 // Pool, and returns it to the caller. 51 // Get may choose to ignore the pool and treat it as empty. 52 // Callers should not assume any relation between values passed to Put and 53 // the values returned by Get. 54 // 55 // If Get would otherwise return nil and p.New is non-nil, Get returns 56 // the result of calling p.New. 57 func (p *Pool) Get() (x interface{}) { 58 p.init() 59 return p.p.Get() 60 }