Skip to content

Commit

Permalink
Store timers in a pool (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
storozhukBM authored Jun 13, 2021
1 parent ee6c0a0 commit f8d9a03
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
24 changes: 22 additions & 2 deletions hedged.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
)
Expand Down Expand Up @@ -149,8 +150,8 @@ func waitResult(ctx context.Context, resultCh <-chan indexedResp, errorCh <-chan
case res := <-resultCh:
return res, nil
default:
timer := time.NewTimer(timeout)
defer timer.Stop()
timer := getTimer(timeout)
defer returnTimer(timer)

select {
case res := <-resultCh:
Expand Down Expand Up @@ -323,3 +324,22 @@ func listFormatFunc(es []error) string {

return fmt.Sprintf("%d errors occurred:\n\t%s\n\n", len(es), strings.Join(points, "\n\t"))
}

var timerPool = sync.Pool{New: func() interface{} {
return time.NewTimer(time.Second)
}}

func getTimer(duration time.Duration) *time.Timer {
timer := timerPool.Get().(*time.Timer)
timer.Reset(duration)
return timer
}

func returnTimer(timer *time.Timer) {
timer.Stop()
select {
case _ = <-timer.C:
default:
}
timerPool.Put(timer)
}
2 changes: 2 additions & 0 deletions hedged_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ func BenchmarkHedgedRequest(b *testing.B) {
}
for _, bm := range benchmarks {
b.Run(fmt.Sprintf("concurrency-%v", bm.concurrency), func(b *testing.B) {
b.ReportAllocs()

target := &FuncRoundTripper{
f: func(request *http.Request) (*http.Response, error) {
rnd := getLocalRand()
Expand Down

0 comments on commit f8d9a03

Please sign in to comment.