1 |
torben |
467 |
package dk.thoerup.circuitbreaker; |
2 |
torben |
393 |
|
3 |
|
|
import java.util.concurrent.atomic.AtomicLong; |
4 |
|
|
|
5 |
torben |
1306 |
import dk.thoerup.circuitbreaker.config.BreakerConfig; |
6 |
torben |
393 |
|
7 |
torben |
1306 |
|
8 |
torben |
3212 |
|
9 |
torben |
424 |
public final class OpenState implements CircuitBreakerState { |
10 |
torben |
393 |
|
11 |
torben |
424 |
final private AtomicLong tripTime = new AtomicLong(0); |
12 |
torben |
393 |
|
13 |
torben |
1306 |
BreakerConfig config; |
14 |
|
|
|
15 |
|
|
public void setTimeout(BreakerConfig config) { |
16 |
|
|
this.config = config; |
17 |
torben |
393 |
} |
18 |
|
|
|
19 |
torben |
3212 |
|
20 |
|
|
public void preInvoke(CircuitBreaker<?> circuitBreaker) throws Exception |
21 |
torben |
393 |
{ |
22 |
|
|
long now = System.currentTimeMillis(); |
23 |
|
|
long elapsed = now - tripTime.get(); |
24 |
|
|
|
25 |
torben |
1306 |
if(elapsed > config.getTimeout()) |
26 |
torben |
393 |
{ |
27 |
|
|
circuitBreaker.attemptReset(); |
28 |
|
|
} |
29 |
|
|
else |
30 |
|
|
{ |
31 |
|
|
throw new CircuitBreakerException("Circuit Breaker is open; calls are failing fast"); |
32 |
|
|
} |
33 |
|
|
} |
34 |
|
|
|
35 |
torben |
3212 |
public void postInvoke(CircuitBreaker<?> circuitBreaker) throws Exception |
36 |
torben |
393 |
{ |
37 |
|
|
// NO OP |
38 |
|
|
} |
39 |
|
|
|
40 |
torben |
3212 |
public void onError(CircuitBreaker<?> circuitBreaker, Exception t) throws Exception |
41 |
torben |
393 |
{ |
42 |
|
|
// NO OP |
43 |
|
|
} |
44 |
|
|
|
45 |
|
|
void trip() |
46 |
|
|
{ |
47 |
|
|
long now = System.currentTimeMillis(); |
48 |
|
|
tripTime.set(now); |
49 |
|
|
} |
50 |
|
|
|
51 |
torben |
397 |
public String getName() { |
52 |
|
|
return "Open"; |
53 |
|
|
} |
54 |
|
|
|
55 |
|
|
public long getTimeout() { |
56 |
torben |
1306 |
return config.getTimeout(); |
57 |
torben |
397 |
} |
58 |
|
|
|
59 |
|
|
public long getElapsed() { |
60 |
|
|
long now = System.currentTimeMillis(); |
61 |
|
|
long elapsed = now - tripTime.get(); |
62 |
|
|
return elapsed; |
63 |
|
|
} |
64 |
|
|
|
65 |
torben |
393 |
} |