Skip to content

Commit

Permalink
Fix data race when querying GetElapsedTime()
Browse files Browse the repository at this point in the history
`ExponentialBackOff.GetElapsedTime()` reads start time which is reset
by `ExponentialBackOff.Reset()` which is called by `run()`, executed
in a goroutine. This creates a data race just by using:

```go
b := NewExponentialBackOff()
ticker := backoff.NewTicker(b)
b.GetElapsedTime()
```

This commit solves this by resetting the backoff timer outside the
goroutine. The ticker test has been updated for this particular data
race.
  • Loading branch information
vincentbernat committed Sep 19, 2017
1 parent 80e08cb commit ff874c0
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
2 changes: 1 addition & 1 deletion ticker.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func NewTicker(b BackOff) *Ticker {
b: ensureContext(b),
stop: make(chan struct{}),
}
t.b.Reset()
go t.run()
runtime.SetFinalizer(t, (*Ticker).Stop)
return t
Expand All @@ -42,7 +43,6 @@ func (t *Ticker) Stop() {
func (t *Ticker) run() {
c := t.c
defer close(c)
t.b.Reset()

// Ticker is guaranteed to tick at least once.
afterC := t.send(time.Now())
Expand Down
4 changes: 4 additions & 0 deletions ticker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ func TestTicker(t *testing.T) {

b := NewExponentialBackOff()
ticker := NewTicker(b)
elapsed := b.GetElapsedTime()
if elapsed > time.Second {
t.Errorf("elapsed time too large: %v", elapsed)
}

var err error
for _ = range ticker.C {
Expand Down

0 comments on commit ff874c0

Please sign in to comment.