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