Codebase list golang-gopkg-eapache-go-resiliency.v1 / eaf0b22
More efficient synchronization Use atomic ops on the state variable. This lets new requests go ahead even when something has the main lock, and lets us simplify that lock to a normal Mutex instead of an RWMutex. Evan Huus 9 years ago
1 changed file(s) with 9 addition(s) and 14 deletion(s). Raw diff Collapse all Expand all
33 import (
44 "errors"
55 "sync"
6 "sync/atomic"
67 "time"
78 )
89
1011 // because the breaker is currently open.
1112 var ErrBreakerOpen = errors.New("circuit breaker is open")
1213
13 type state int
14
1514 const (
16 closed state = iota
15 closed uint32 = iota
1716 open
1817 halfOpen
1918 )
2322 errorThreshold, successThreshold int
2423 timeout time.Duration
2524
26 lock sync.RWMutex
27 state state
25 lock sync.Mutex
26 state uint32
2827 errors, successes int
2928 lastError time.Time
3029 }
4645 // already open, or it will run the given function and pass along its return
4746 // value. It is safe to call Run concurrently on the same Breaker.
4847 func (b *Breaker) Run(work func() error) error {
49 b.lock.RLock()
50 state := b.state
51 b.lock.RUnlock()
48 state := atomic.LoadUint32(&b.state)
5249
5350 if state == open {
5451 return ErrBreakerOpen
6360 // the return value of the function. It is safe to call Go concurrently on the
6461 // same Breaker.
6562 func (b *Breaker) Go(work func() error) error {
66 b.lock.RLock()
67 state := b.state
68 b.lock.RUnlock()
63 state := atomic.LoadUint32(&b.state)
6964
7065 if state == open {
7166 return ErrBreakerOpen
7974 return nil
8075 }
8176
82 func (b *Breaker) doWork(state state, work func() error) error {
77 func (b *Breaker) doWork(state uint32, work func() error) error {
8378 var panicValue interface{}
8479
8580 result := func() error {
158153 b.changeState(halfOpen)
159154 }
160155
161 func (b *Breaker) changeState(newState state) {
156 func (b *Breaker) changeState(newState uint32) {
162157 b.errors = 0
163158 b.successes = 0
164 b.state = newState
159 atomic.StoreUint32(&b.state, newState)
165160 }