Quellcode durchsuchen

Add 'Close' function to properly release all resources for a host pool.

review comments

review comments
James Wu vor 11 Jahren
Ursprung
Commit
8fedab77fc
2 geänderte Dateien mit 24 neuen und 4 gelöschten Zeilen
  1. 15 4
      epsilon_greedy.go
  2. 9 0
      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()
@@ -73,10 +79,15 @@ func (p *epsilonGreedyHostPool) SetEpsilon(newEpsilon float32) {
 
 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() {

+ 9 - 0
hostpool.go

@@ -45,6 +45,9 @@ type HostPool interface {
 
 	ResetAll()
 	Hosts() []string
+
+	// Close the hostpool and release all resources.
+	Close()
 }
 
 type standardHostPool struct {
@@ -155,6 +158,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()