Skip to content

Commit

Permalink
use a generation number on JitterTicker to prevent latent ticks from …
Browse files Browse the repository at this point in the history
…arriving
  • Loading branch information
bradenaw committed Sep 9, 2023
1 parent 5f0e378 commit d72bc66
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion xtime/xtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type JitterTicker struct {
c chan time.Time
m sync.Mutex
d time.Duration
gen int
jitter time.Duration
timer *time.Timer
}
Expand Down Expand Up @@ -91,9 +92,15 @@ func (t *JitterTicker) schedule() {
t.timer.Stop()
}
next := t.d + time.Duration(rand.Int63n(int64(t.jitter*2))) - (t.jitter)

// To prevent a latent goroutine already spawned but not yet running the below function from
// delivering a tick after Stop/Reset.
t.gen++
gen := t.gen

t.timer = time.AfterFunc(next, func() {
t.m.Lock()
if t.timer != nil {
if t.gen == gen {
select {
case t.c <- time.Now():
default:
Expand Down

0 comments on commit d72bc66

Please sign in to comment.