--- CircuitBreaker/src/dk/thoerup/circuitbreaker/CircuitBreaker.java 2010/03/08 10:12:59 627 +++ CircuitBreaker/src/dk/thoerup/circuitbreaker/CircuitBreaker.java 2011/04/19 17:12:27 1314 @@ -1,6 +1,12 @@ package dk.thoerup.circuitbreaker; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import dk.thoerup.circuitbreaker.config.BreakerConfig; +import dk.thoerup.circuitbreaker.config.StaticConfig; +import dk.thoerup.circuitbreaker.notification.NotiferHelper; import dk.thoerup.circuitbreaker.notification.Notifier; import dk.thoerup.circuitbreaker.notification.NullNotifier; @@ -51,11 +57,16 @@ private String name; + private ExecutorService executor = null; private Notifier notifier = new NullNotifier(); - public CircuitBreaker(String name, int threshold, long timeoutMS) { - closed.setThreshold(threshold); - open.setTimeout(timeoutMS); + /*public CircuitBreaker(String name, int threshold, int timeoutMS) { + this(name, new StaticConfig(threshold, timeoutMS) ); + }*/ + + public CircuitBreaker(String name, BreakerConfig config) { + closed.setThreshold(config); + open.setTimeout(config); this.name = name; @@ -63,6 +74,12 @@ internalReset(); } + public synchronized void shutdown() { + if (executor != null) { + executor.shutdown(); + } + } + public Object invoke(CircuitInvocation invocation) throws Exception { @@ -82,21 +99,30 @@ } public void tripBreaker() { - synchronized(this) { + commonTripBreaker(Notifier.Event.BreakerTripped); + } + + //a re-trip should basically do the same as a normal trip, but it is here just to differentiate the two different events + public void retripBreaker() { + commonTripBreaker(Notifier.Event.BreakerRetripped); + } + + private void commonTripBreaker(Notifier.Event event) { + synchronized(this) { if (currentState != open) { // TODO:Is this conditional necessary ?? open.trip(); currentState = open; - notifier.sendNotification(name, Notifier.Event.BreakerTripped); + notifier.sendNotification(this, event); } - } + } } - + public void attemptReset() { synchronized(this) { if (currentState != halfOpen) { // TODO:Is this conditional necessary ?? currentState = halfOpen; - notifier.sendNotification(name, Notifier.Event.BreakerAttemptReset); + notifier.sendNotification(this, Notifier.Event.BreakerAttemptReset); } } @@ -106,7 +132,7 @@ synchronized(this) { if (currentState != closed) { // TODO: Is this conditional necessary ?? internalReset(); - notifier.sendNotification(name, Notifier.Event.BreakerReset); + notifier.sendNotification(this, Notifier.Event.BreakerReset); } } } @@ -168,8 +194,18 @@ this.notifier = notifier; } - public String getNotifierName() { - return notifier.getClass().getName(); + public String getNotifierName() { + return NotiferHelper.getName(notifier); + } + + public synchronized ExecutorService getExecutor() { + + if (executor == null) { + executor = Executors.newFixedThreadPool(1); + } + + return executor; + } }