0% completed
Let’s implement a basic Circuit Breaker in Java to illustrate the core algorithm. We won’t use any external libraries – just a simple class to demonstrate the state logic:
public class CircuitBreaker { private enum State { CLOSED, OPEN, HALF_OPEN } private State state = State.CLOSED; private int failureCount = 0; private final int failureThreshold; private final long openTimeout; // how long to stay open before trying half-open private long lastFailureTime = 0; public CircuitBreaker(int failureThreshold, long openTimeout) { this.failureThreshold = failureThreshold; this.openTimeout = openTimeout; } public synchronized <T> T call(Callable<T> remoteCall) throws Exception { // 1. If breaker is OPEN, check if timeout has passed to allow a half-open trial if (state == State.OPEN) { long timeSinceFailure = System.currentTimeMillis() - lastFailureTime; if (timeSinceFailure < openTimeout) { // Still within open timeout, reject the call fast throw new IllegalStateException("Circuit is OPEN. Failing fast without calling remote service."); } else { // Timeout passed, move to half-open and allow a trial call state = State.HALF_OPEN; } } // 2. Try to invoke the remote call (allowed if state is CLOSED or HALF_OPEN) try { T result = remoteCall.call(); // Call succeeded. Reset failure count and close the circuit (if it was half-open, now fully close it). failureCount = 0; state = State.CLOSED; return result; } catch (Exception e) { // Call failed. Increase the failure count. failureCount++; lastFailureTime = System.currentTimeMillis(); if (failureCount >= failureThreshold) { // Too many failures, trip the circuit to OPEN state. state = State.OPEN; } throw e; // Propagate the exception (or could return a fallback here) } } }
In the code above, CircuitBreaker
tracks the number of failures and the current state. The call
method wraps the execution of a remote operation (passed as a Callable<T>
). Here’s how it works:
-
Before calling the remote service, it checks the state. If the circuit is OPEN, the code checks if the open timeout has elapsed. If not (meaning it's too soon to retry), it fails fast by throwing an exception (
IllegalStateException
in this case) instead of calling the remote service. If the timeout has elapsed, the breaker moves to HALF_OPEN state, allowing one trial call to proceed. -
Executing the call: If the state is Closed or Half-Open, it attempts the
remoteCall
. This is where your actual remote service logic would run. -
After the call returns: If the call succeeds, we reset the failure counter and set the state to CLOSED. (In Half-Open, a success means the service is back, so we fully close the circuit again. In Closed, a success just keeps it closed and can reset any past failure count.) If the call throws an exception or times out, we increment the failure count and record the time of failure. If the failures have reached the
failureThreshold
, the circuit switches to OPEN (tripped). The exception is rethrown to the caller – in a real system, the caller might catch this and fall back to some default behavior.
Using this CircuitBreaker
is straightforward. For example:
CircuitBreaker cb = new CircuitBreaker(3, 10000); // trip after 3 failures, 10s timeout try { String data = cb.call(() -> unreliableService.getData()); // use data... } catch (Exception e) { // Handle fallback logic because service call failed or circuit is open useCachedData(); }
In this example, if unreliableService.getData()
fails 3 times in a row, the circuit breaker will open. Further attempts within 10 seconds will immediately throw an exception without calling getData()
at all – the circuit breaker is preventing more failures. After 10 seconds, the next call will be allowed to try the service again (half-open). If that next call succeeds, the circuit closes and things go back to normal. If it fails, the circuit re-opens and will block calls for another 10 seconds.
This is a simplistic implementation to demonstrate the concept. In production, a circuit breaker might be more sophisticated – handling thread-safety, using a rolling window of failure metrics, or integrating with monitoring systems – but the core idea is the same.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible