1 |
package dk.thoerup.curcuitbreaker; |
package dk.thoerup.circuitbreaker; |
2 |
|
|
3 |
import java.util.concurrent.atomic.*; |
import java.util.concurrent.atomic.AtomicInteger; |
4 |
|
|
5 |
|
import dk.thoerup.circuitbreaker.config.BreakerConfig; |
6 |
|
|
7 |
|
|
|
public class ClosedState implements CircuitBreakerState { |
|
8 |
|
|
9 |
AtomicInteger failureCount = new AtomicInteger(0); |
public final class ClosedState implements CircuitBreakerState { |
10 |
AtomicInteger failureThreshold = new AtomicInteger(0); |
|
11 |
|
final AtomicInteger failureCount = new AtomicInteger(0); |
12 |
|
|
13 |
|
|
14 |
|
BreakerConfig config; |
15 |
|
|
16 |
public void setThreshold(int threshold) { |
public void setThreshold(BreakerConfig config) { |
17 |
failureThreshold.set( threshold ); |
this.config = config; |
18 |
} |
} |
19 |
|
|
20 |
public void preInvoke(CircuitBreaker circuitBreaker) throws Throwable |
public void preInvoke(CircuitBreaker circuitBreaker) throws Exception |
21 |
{ |
{ |
22 |
// NO OP |
// NO OP |
23 |
} |
} |
24 |
|
|
25 |
public void postInvoke(CircuitBreaker circuitBreaker) throws Throwable |
public void postInvoke(CircuitBreaker circuitBreaker) throws Exception |
26 |
{ |
{ |
27 |
resetFailureCount(); |
resetFailureCount(); |
28 |
} |
} |
29 |
|
|
30 |
public void onError(CircuitBreaker circuitBreaker, Throwable t) throws Throwable |
public void onError(CircuitBreaker circuitBreaker, Exception t) throws Exception |
31 |
{ |
{ |
32 |
int currentCount = failureCount.incrementAndGet(); |
int currentCount = failureCount.incrementAndGet(); |
33 |
int threshold = failureThreshold.get(); |
int threshold = config.getTreshold(); |
34 |
if(currentCount >= threshold) |
if(currentCount >= threshold) |
35 |
circuitBreaker.tripBreaker(); |
circuitBreaker.tripBreaker(); |
36 |
} |
} |
37 |
|
|
38 |
private void resetFailureCount() { |
public void resetFailureCount() { |
39 |
failureCount.set(0); |
failureCount.set(0); |
40 |
} |
} |
41 |
|
|
48 |
} |
} |
49 |
|
|
50 |
public int getThreshold() { |
public int getThreshold() { |
51 |
return failureThreshold.get(); |
return config.getTreshold(); |
52 |
} |
} |
53 |
} |
} |