Debian Codegraph @

timer.go

raw
1 // Copyright 2017-2022 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
14 package nats
15
16 import (
17 "sync"
18 "time"
19 )
20
21 // global pool of *time.Timer's. can be used by multiple goroutines concurrently.
22 var globalTimerPool timerPool
23
24 // timerPool provides GC-able pooling of *time.Timer's.
25 // can be used by multiple goroutines concurrently.
26 type timerPool struct {
27 p sync.Pool
28 }
29
30 // Get returns a timer that completes after the given duration.
31 func (tp *timerPool) Get(d time.Duration) *time.Timer {
32 if t, ok := tp.p.Get().(*time.Timer); ok && t != nil {
33 t.Reset(d)
34 return t
35 }
36
37 return time.NewTimer(d)
38 }
39
40 // Put pools the given timer.
41 //
42 // There is no need to call t.Stop() before calling Put.
43 //
44 // Put will try to stop the timer before pooling. If the
45 // given timer already expired, Put will read the unreceived
46 // value if there is one.
47 func (tp *timerPool) Put(t *time.Timer) {
48 if !t.Stop() {
49 select {
50 case <-t.C:
51 default:
52 }
53 }
54
55 tp.p.Put(t)
56 }