2
0

Store resource creation time

This commit is contained in:
Jack Christensen
2018-12-26 15:35:13 -06:00
parent 99fde4bb49
commit df3f83d1f7
2 changed files with 14 additions and 4 deletions
+13 -4
View File
@@ -21,9 +21,10 @@ type Constructor func(ctx context.Context) (res interface{}, err error)
type Destructor func(res interface{})
type Resource struct {
value interface{}
pool *Pool
status byte
value interface{}
pool *Pool
creationTime time.Time
status byte
}
func (res *Resource) Value() interface{} {
@@ -53,6 +54,14 @@ func (res *Resource) Hijack() {
res.pool.hijackAcquiredResource(res)
}
// CreationTime returns when the resource was created by the pool.
func (res *Resource) CreationTime() time.Time {
if res.status != resourceStatusAcquired {
panic("tried to use resource that is not acquired")
}
return res.creationTime
}
// Pool is a thread-safe resource pool.
type Pool struct {
cond *sync.Cond
@@ -232,7 +241,7 @@ func (p *Pool) Acquire(ctx context.Context) (*Resource, error) {
// If there is room to create a resource do so
if len(p.allResources) < p.maxSize {
res := &Resource{pool: p, status: resourceStatusConstructing}
res := &Resource{pool: p, creationTime: startTime, status: resourceStatusConstructing}
p.allResources = append(p.allResources, res)
p.destructWG.Add(1)
p.cond.L.Unlock()
+1
View File
@@ -76,6 +76,7 @@ func TestPoolAcquireCreatesResourceWhenNoneIdle(t *testing.T) {
res, err := pool.Acquire(context.Background())
require.NoError(t, err)
assert.Equal(t, 1, res.Value())
assert.WithinDuration(t, time.Now(), res.CreationTime(), time.Second)
res.Release()
}