Skip to content

Commit

Permalink
Replace use of reflect.Select() with go-routines
Browse files Browse the repository at this point in the history
  • Loading branch information
jsoriano committed May 29, 2018
1 parent 9ac6b30 commit 41c6e10
Showing 1 changed file with 14 additions and 29 deletions.
43 changes: 14 additions & 29 deletions libbeat/autodiscover/providers/jolokia/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package jolokia
import (
"encoding/json"
"net"
"reflect"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -102,7 +101,7 @@ func (d *Discovery) Start() {

// Stop stops discovery probes
func (d *Discovery) Stop() {
d.stop <- struct{}{}
close(d.stop)
close(d.events)
}

Expand All @@ -113,35 +112,21 @@ func (d *Discovery) Events() <-chan Event {
}

func (d *Discovery) run() {
var cases []reflect.SelectCase
for _, i := range d.Interfaces {
// Send a probe on each interface when starting
d.sendProbe(i)

// And then one after each interval
ticker := time.NewTicker(i.Interval)
defer ticker.Stop()
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ticker.C),
})
}

// As a last case, place the stop channel so the loop can be gracefuly stopped
stopIndex := len(cases)
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(d.stop),
})

for {
chosen, _, _ := reflect.Select(cases)
if chosen == stopIndex {
return
}
d.sendProbe(d.Interfaces[chosen])
d.checkStopped()
i := i
go func() {
for {
d.sendProbe(i)
d.checkStopped()
select {
case <-time.After(i.Interval):
case <-d.stop:
return
}
}
}()
}
<-d.stop
}

func (d *Discovery) interfaces(name string) ([]net.Interface, error) {
Expand Down

0 comments on commit 41c6e10

Please sign in to comment.