Skip to content

Commit

Permalink
Simplify timer cleanup
Browse files Browse the repository at this point in the history
The timer channels are created with a buffer. Because we aren't reusing them,
we don't need to worry about draining that channel; the internal
goroutine will still be able to write to the buffer and exit gracefully,
at which point the GC will clean it all up.

We *do* still need to call `Stop()` to tell the timer to clean up
immediately, as otherwise it will run for its full duration which (in a
tight loop) can cause timer goroutines to pile up.
  • Loading branch information
eapache committed Jan 13, 2024
1 parent b912f08 commit 25cd6b0
Show file tree
Hide file tree
Showing 3 changed files with 3 additions and 12 deletions.
5 changes: 1 addition & 4 deletions deadline/deadline.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ func (d *Deadline) Run(work func(<-chan struct{}) error) error {
timer := time.NewTimer(d.timeout)
select {
case ret := <-result:
if !timer.Stop() {
<-timer.C
}

timer.Stop()
return ret
case <-timer.C:
close(stopper)
Expand Down
5 changes: 1 addition & 4 deletions retrier/retrier.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,7 @@ func (r *Retrier) sleep(ctx context.Context, timer *time.Timer) error {
case <-timer.C:
return nil
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}

timer.Stop()
return ctx.Err()
}
}
Expand Down
5 changes: 1 addition & 4 deletions semaphore/semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ func (s *Semaphore) Acquire() error {
timer := time.NewTimer(s.timeout)
select {
case s.sem <- struct{}{}:
if !timer.Stop() {
<-timer.C
}

timer.Stop()
return nil
case <-timer.C:
return ErrNoTickets
Expand Down

0 comments on commit 25cd6b0

Please sign in to comment.