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