Last active
December 26, 2015 08:49
-
-
Save hkolbeck/7124655 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ThingPool struct { | |
pool chan *Thing | |
generator func() *Thing | |
destructor func(*Thing) | |
} | |
func NewThingPool(poolSize int, generator func() *Thing, destructor func(*Thing)) *ThingPool { | |
p := &ThingPool{ | |
pool : make(chan *Thing, poolsize), | |
generator : generator, | |
destructor : destructor, | |
} | |
for i := 0; i < poolSize; i++ { | |
p.pool <- generator() | |
} | |
return p | |
} | |
func (p *ThingPool) Acquire(maxWait time.Duration) *Thing { | |
select { | |
case t := <-p.pool: | |
return t | |
default: | |
timeout := time.After(maxWait) | |
select { | |
case t := <-p.pool: | |
return t | |
case <-timeout: | |
return p.generator() | |
} | |
} | |
} | |
func (p *ThingPool) Release(t *Thing) { | |
select { | |
case p.pool <- t: | |
default: | |
p.destructor(t) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment