Ver código fonte

Merge pull request #3 from hailocab/upstream-merge

Upstream merge
Daniel Cannon 10 anos atrás
pai
commit
e80d13ce29
2 arquivos alterados com 25 adições e 5 exclusões
  1. 15 4
      epsilon_greedy.go
  2. 10 1
      hostpool.go

+ 15 - 4
epsilon_greedy.go

@@ -17,7 +17,6 @@ func (r *epsilonHostPoolResponse) Mark(err error) {
 		r.ended = time.Now()
 		doMark(err, r)
 	})
-
 }
 
 type epsilonGreedyHostPool struct {
@@ -26,6 +25,7 @@ type epsilonGreedyHostPool struct {
 	decayDuration          time.Duration
 	EpsilonValueCalculator // embed the epsilonValueCalculator
 	timer
+	quit chan bool
 }
 
 // Construct an Epsilon Greedy HostPool
@@ -54,6 +54,7 @@ func NewEpsilonGreedy(hosts []string, decayDuration time.Duration, calc EpsilonV
 		decayDuration:          decayDuration,
 		EpsilonValueCalculator: calc,
 		timer: &realTimer{},
+		quit:  make(chan bool),
 	}
 
 	// allocate structures
@@ -65,6 +66,11 @@ func NewEpsilonGreedy(hosts []string, decayDuration time.Duration, calc EpsilonV
 	return p
 }
 
+func (p *epsilonGreedyHostPool) Close() {
+	// No need to do p.quit <- true as close(p.quit) does the trick.
+	close(p.quit)
+}
+
 func (p *epsilonGreedyHostPool) SetEpsilon(newEpsilon float32) {
 	p.Lock()
 	defer p.Unlock()
@@ -83,10 +89,15 @@ func (p *epsilonGreedyHostPool) SetHosts(hosts []string) {
 
 func (p *epsilonGreedyHostPool) epsilonGreedyDecay() {
 	durationPerBucket := p.decayDuration / epsilonBuckets
-	ticker := time.Tick(durationPerBucket)
+	ticker := time.NewTicker(durationPerBucket)
 	for {
-		<-ticker
-		p.performEpsilonGreedyDecay()
+		select {
+		case <-p.quit:
+			ticker.Stop()
+			return
+		case <-ticker.C:
+			p.performEpsilonGreedyDecay()
+		}
 	}
 }
 func (p *epsilonGreedyHostPool) performEpsilonGreedyDecay() {

+ 10 - 1
hostpool.go

@@ -50,6 +50,9 @@ type HostPool interface {
 	ReturnUnhealthy(v bool)
 	Hosts() []string
 	SetHosts([]string)
+
+	// Close the hostpool and release all resources.
+	Close()
 }
 
 type standardHostPool struct {
@@ -197,6 +200,12 @@ func (p *standardHostPool) doResetAll() {
 	}
 }
 
+func (p *standardHostPool) Close() {
+	for _, h := range p.hosts {
+		h.dead = true
+	}
+}
+
 func (p *standardHostPool) markSuccess(hostR HostPoolResponse) {
 	host := hostR.Host()
 	p.Lock()
@@ -226,7 +235,7 @@ func (p *standardHostPool) markFailed(hostR HostPoolResponse) {
 
 }
 func (p *standardHostPool) Hosts() []string {
-	hosts := make([]string, len(p.hosts))
+	hosts := make([]string, 0, len(p.hosts))
 	for host := range p.hosts {
 		hosts = append(hosts, host)
 	}