diff --git a/README.md b/README.md index 21266d2..cec9981 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,6 @@ Puddle is a generic resource pool library for Go. ## TODO -* Min pool size * Max resource lifetime * Max resource uses * Max resource idle time diff --git a/pool.go b/pool.go index 6762123..3610f3b 100644 --- a/pool.go +++ b/pool.go @@ -37,6 +37,7 @@ type Pool struct { allResources map[interface{}]*resourceWrapper availableResources []*resourceWrapper + minSize int maxSize int closed bool @@ -84,6 +85,30 @@ func (p *Pool) Size() int { return n } +// MinSize returns the current minimum size of the pool. +func (p *Pool) MinSize() int { + p.cond.L.Lock() + n := p.minSize + p.cond.L.Unlock() + return n +} + +// SetMinSize sets the minimum size of the pool. It panics if n < 0. +func (p *Pool) SetMinSize(n int) { + if n < 0 { + panic("pool MinSize cannot be < 0") + } + p.cond.L.Lock() + p.minSize = n + + for len(p.allResources) < p.minSize { + createResChan, createErrChan := p.startCreate() + p.backgroundFinishCreate(createResChan, createErrChan) + } + + p.cond.L.Unlock() +} + // MaxSize returns the current maximum size of the pool. func (p *Pool) MaxSize() int { p.cond.L.Lock() diff --git a/pool_test.go b/pool_test.go index 2fa1e6c..df7cb9a 100644 --- a/pool_test.go +++ b/pool_test.go @@ -50,6 +50,16 @@ func TestPoolGetCreatesResourceWhenNoneAvailable(t *testing.T) { pool.Return(res) } +func TestPoolSetMinSizeImmediatelyCreatesNewResources(t *testing.T) { + var createCalls Counter + createFunc := func() (interface{}, error) { + return createCalls.Next(), nil + } + pool := puddle.NewPool(createFunc, stubCloseRes) + pool.SetMinSize(2) + assert.Equal(t, 2, pool.Size()) +} + func TestPoolGetDoesNotCreatesResourceWhenItWouldExceedMaxSize(t *testing.T) { var createCalls Counter createFunc := func() (interface{}, error) {