NewBreaker creates a Breaker with the desired queue depth, concurrency limit and initial capacity.
(params BreakerParams)
| 55 | // NewBreaker creates a Breaker with the desired queue depth, |
| 56 | // concurrency limit and initial capacity. |
| 57 | func NewBreaker(params BreakerParams) *Breaker { |
| 58 | if params.QueueDepth <= 0 { |
| 59 | panic(fmt.Sprintf("Queue depth must be greater than 0. Got %v.", params.QueueDepth)) |
| 60 | } |
| 61 | if params.MaxConcurrency < 0 { |
| 62 | panic(fmt.Sprintf("Max concurrency must be 0 or greater. Got %v.", params.MaxConcurrency)) |
| 63 | } |
| 64 | if params.InitialCapacity < 0 || params.InitialCapacity > params.MaxConcurrency { |
| 65 | panic(fmt.Sprintf("Initial capacity must be between 0 and max concurrency. Got %v.", params.InitialCapacity)) |
| 66 | } |
| 67 | |
| 68 | b := &Breaker{ |
| 69 | totalSlots: int64(params.QueueDepth + params.MaxConcurrency), |
| 70 | sem: newSemaphore(params.MaxConcurrency, params.InitialCapacity), |
| 71 | } |
| 72 | |
| 73 | // Allocating the closure returned by Reserve here avoids an allocation in Reserve. |
| 74 | b.release = func() { |
| 75 | b.sem.release() |
| 76 | b.releasePending() |
| 77 | } |
| 78 | |
| 79 | return b |
| 80 | } |
| 81 | |
| 82 | // tryAcquirePending tries to acquire a slot on the pending "queue". |
| 83 | func (b *Breaker) tryAcquirePending() bool { |