improve package gpool
-// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
+// Copyright GoFrame gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
@@ -19,18 +19,10 @@ import (
// Pool is an Object-Reusable Pool.
type Pool struct {
- // Available/idle items list.
- list *glist.List
-
- // Whether the pool is closed.
- closed *gtype.Bool
-
- // Time To Live for pool items.
- TTL time.Duration
-
- // Callback function to create pool item.
- NewFunc func() (interface{}, error)
-
+ list *glist.List // Available/idle items list.
+ closed *gtype.Bool // Whether the pool is closed.
+ TTL time.Duration // Time To Live for pool items.
+ NewFunc func() (interface{}, error) // Callback function to create pool item.
// ExpireFunc is the for expired items destruction.
// This function needs to be defined when the pool items
// need to perform additional destruction operations.
@@ -40,8 +32,8 @@ type Pool struct {
// Pool item.
type poolItem struct {
- expire int64 // Expire timestamp in milliseconds.
value interface{} // Item value.
+ expireAt int64 // Expire timestamp in milliseconds.
}
// Creation function for object.
@@ -80,11 +72,11 @@ func (p *Pool) Put(value interface{}) error {
value: value,
}
if p.TTL == 0 {
- item.expire = 0
+ item.expireAt = 0
} else {
// As for Golang version < 1.13, there's no method Milliseconds for time.Duration.
// So we need calculate the milliseconds using its nanoseconds value.
- item.expire = gtime.TimestampMilli() + p.TTL.Nanoseconds()/1000000
+ item.expireAt = gtime.TimestampMilli() + p.TTL.Nanoseconds()/1000000
}
p.list.PushBack(item)
return nil
@@ -112,9 +104,10 @@ func (p *Pool) Get() (interface{}, error) {
for !p.closed.Val() {
if r := p.list.PopFront(); r != nil {
f := r.(*poolItem)
- if f.expire == 0 || f.expire > gtime.TimestampMilli() {
+ if f.expireAt == 0 || f.expireAt > gtime.TimestampMilli() {
return f.value, nil
} else if p.ExpireFunc != nil {
+ // TODO: move expire function calling asynchronously from `Get` operation.
p.ExpireFunc(f.value)
}
} else {
@@ -171,9 +164,9 @@ func (p *Pool) checkExpireItems() {
}
if r := p.list.PopFront(); r != nil {
item := r.(*poolItem)
- latestExpire = item.expire
+ latestExpire = item.expireAt
// TODO improve the auto-expiration mechanism of the pool.
- if item.expire > timestampMilli {
+ if item.expireAt > timestampMilli {
p.list.PushFront(item)
break
}
