pool.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package entry
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/kataras/iris/v12/cache/cfg"
  6. "github.com/kataras/iris/v12/core/memstore"
  7. )
  8. // Pool is the context pool, it's used inside router and the framework by itself.
  9. type Pool struct {
  10. pool *sync.Pool
  11. }
  12. // NewPool creates and returns a new context pool.
  13. func NewPool() *Pool {
  14. return &Pool{pool: &sync.Pool{New: func() any { return &Entry{} }}}
  15. }
  16. // func NewPool(newFunc func() any) *Pool {
  17. // return &Pool{pool: &sync.Pool{New: newFunc}}
  18. // }
  19. // Acquire returns an Entry from pool.
  20. // See Release.
  21. func (c *Pool) Acquire(lifeDuration time.Duration, r *Response, onExpire func()) *Entry {
  22. // If the given duration is not <=0 (which means finds from the headers)
  23. // then we should check for the MinimumCacheDuration here
  24. if lifeDuration >= 0 && lifeDuration < cfg.MinimumCacheDuration {
  25. lifeDuration = cfg.MinimumCacheDuration
  26. }
  27. e := c.pool.Get().(*Entry)
  28. lt := memstore.NewLifeTime()
  29. lt.Begin(lifeDuration, func() {
  30. onExpire()
  31. c.release(e)
  32. })
  33. e.reset(lt, r)
  34. return e
  35. }
  36. // Release puts an Entry back to its pull, this function releases its resources.
  37. // See Acquire.
  38. func (c *Pool) release(e *Entry) {
  39. e.response.body = nil
  40. e.response.headers = nil
  41. e.response.statusCode = 0
  42. e.response = nil
  43. // do not call it, it contains a lock too, release is controlled only inside the Acquire itself when the entry is expired.
  44. // if e.lifeTime != nil {
  45. // e.lifeTime.ExpireNow() // stop any opening timers if force released.
  46. // }
  47. c.pool.Put(e)
  48. }
  49. // Release can be called by custom stores to release an entry.
  50. func (c *Pool) Release(e *Entry) {
  51. if e.lifeTime != nil {
  52. e.lifeTime.ExpireNow() // stop any opening timers if force released.
  53. }
  54. c.release(e)
  55. }