1 |
package dk.thoerup.curcuitbreaker; |
package dk.thoerup.circuitbreaker; |
2 |
|
|
3 |
|
|
4 |
import dk.thoerup.curcuitbreaker.notification.Notifier; |
import dk.thoerup.circuitbreaker.notification.Notifier; |
5 |
import dk.thoerup.curcuitbreaker.notification.NullNotifier; |
import dk.thoerup.circuitbreaker.notification.NullNotifier; |
6 |
|
|
7 |
/* Simple CircuitBreaker implementation - snipped from http://www.jroller.com/kenwdelong/entry/circuit_breaker_in_java |
/* Simple CircuitBreaker implementation - snipped from http://www.jroller.com/kenwdelong/entry/circuit_breaker_in_java |
8 |
* |
* |
31 |
try { |
try { |
32 |
String s = (String) cb.invoke(new TestInvocation("http://rafiki/test")); |
String s = (String) cb.invoke(new TestInvocation("http://rafiki/test")); |
33 |
response.getWriter().print(s); |
response.getWriter().print(s); |
34 |
} catch (Throwable e) { |
} catch (Exception e) { |
35 |
logger.warning( e.getMessage() ); |
logger.warning( e.getMessage() ); |
36 |
response.sendError(500); |
response.sendError(500); |
37 |
return; |
return; |
43 |
|
|
44 |
public class CircuitBreaker{ |
public class CircuitBreaker{ |
45 |
|
|
46 |
private CircuitBreakerState currentState; |
private volatile CircuitBreakerState currentState; |
47 |
|
|
48 |
private final OpenState open = new OpenState(); |
private final OpenState open = new OpenState(); |
49 |
private final HalfOpenState halfOpen = new HalfOpenState(); |
private final HalfOpenState halfOpen = new HalfOpenState(); |
63 |
} |
} |
64 |
|
|
65 |
|
|
66 |
public Object invoke(CircuitInvocation invocation) throws Throwable |
public Object invoke(CircuitInvocation invocation) throws Exception |
67 |
{ |
{ |
68 |
Object result = null; |
Object result = null; |
69 |
try |
try |
72 |
result = invocation.proceed(); |
result = invocation.proceed(); |
73 |
getState().postInvoke(this); |
getState().postInvoke(this); |
74 |
} |
} |
75 |
catch(Throwable t) |
catch(Exception e) |
76 |
{ |
{ |
77 |
getState().onError(this, t); |
getState().onError(this, e); |
78 |
throw t; |
throw e; |
79 |
} |
} |
80 |
return result; |
return result; |
81 |
} |
} |
104 |
public void reset() { |
public void reset() { |
105 |
synchronized(this) { |
synchronized(this) { |
106 |
if (currentState != closed) { // TODO: Is this conditional necessary ?? |
if (currentState != closed) { // TODO: Is this conditional necessary ?? |
107 |
|
closed.resetFailureCount(); |
108 |
currentState = closed; |
currentState = closed; |
109 |
notifier.sendNotification(name, Notifier.Event.BreakerReset); |
notifier.sendNotification(name, Notifier.Event.BreakerReset); |
110 |
} |
} |
118 |
} |
} |
119 |
} |
} |
120 |
|
|
121 |
|
public boolean isClosed() { |
122 |
|
return (getState() == closed); |
123 |
|
} |
124 |
|
|
125 |
|
public boolean isOpen() { |
126 |
|
return (getState() == open); |
127 |
|
} |
128 |
|
|
129 |
public String getName() { |
public String getName() { |
130 |
return name; |
return name; |
131 |
} |
} |