package dk.thoerup.curcuitbreaker; import java.util.logging.Logger; /* Simple CircuitBreaker implementation - snipped from http://www.jroller.com/kenwdelong/entry/circuit_breaker_in_java * * example of how it can be used private CircuitBreaker cb = new CircuitBreaker("test", 5, 10000); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { class TestInvocation implements CircuitInvocation { String url; public TestInvocation(String url) { this.url = url; } public Object proceed() throws Exception{ URL u = new URL(url); URLConnection c = u.openConnection(); c.connect(); InputStream in = c.getInputStream(); in.close(); return "hello"; } } try { String s = (String) cb.invoke(new TestInvocation("http://rafiki/test")); response.getWriter().print(s); } catch (Throwable e) { logger.warning( e.getMessage() ); response.sendError(500); return; } } */ public class CircuitBreaker{ Logger logger = Logger.getLogger(CircuitBreaker.class.getName()); private CircuitBreakerState currentState; private OpenState open = new OpenState(); private HalfOpenState halfOpen = new HalfOpenState(); private ClosedState closed = new ClosedState(); private String name; public CircuitBreaker(String name, int threshold, long timeoutMS) { closed.setThreshold(threshold); open.setTimeout(timeoutMS); this.name = name; reset(); } public Object invoke(CircuitInvocation invocation) throws Throwable { Object result = null; try { getState().preInvoke(this); result = invocation.proceed(); getState().postInvoke(this); } catch(Throwable t) { getState().onError(this, t); throw t; } return result; } public void tripBreaker() { synchronized(this) { currentState = open; open.trip(); logger.warning("Circuitbreaker tripBreaker - " + name); } } public void attemptReset() { synchronized(this) { currentState = halfOpen; logger.warning("Circuitbreaker attemptReset - " + name); } } public void reset() { synchronized(this) { currentState = closed; logger.warning("Circuitbreaker reset - " + name); } } private CircuitBreakerState getState() { synchronized(this) { return currentState; } } }