timer.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2017-2018 The NATS Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package nats
  14. import (
  15. "sync"
  16. "time"
  17. )
  18. // global pool of *time.Timer's. can be used by multiple goroutines concurrently.
  19. var globalTimerPool timerPool
  20. // timerPool provides GC-able pooling of *time.Timer's.
  21. // can be used by multiple goroutines concurrently.
  22. type timerPool struct {
  23. p sync.Pool
  24. }
  25. // Get returns a timer that completes after the given duration.
  26. func (tp *timerPool) Get(d time.Duration) *time.Timer {
  27. if t, _ := tp.p.Get().(*time.Timer); t != nil {
  28. t.Reset(d)
  29. return t
  30. }
  31. return time.NewTimer(d)
  32. }
  33. // Put pools the given timer.
  34. //
  35. // There is no need to call t.Stop() before calling Put.
  36. //
  37. // Put will try to stop the timer before pooling. If the
  38. // given timer already expired, Put will read the unreceived
  39. // value if there is one.
  40. func (tp *timerPool) Put(t *time.Timer) {
  41. if !t.Stop() {
  42. select {
  43. case <-t.C:
  44. default:
  45. }
  46. }
  47. tp.p.Put(t)
  48. }