Circuit Breaker State Machine (Java)

Wrap a failing dependency in a breaker: consecutive failures trip it to OPEN and later calls fast-fail instead of hammering a dead upstream.

JavaResilience

Code

snippet
public class CircuitBreaker {

    enum State { CLOSED, OPEN }

    private State state = State.CLOSED;
    private int failures = 0;
    private final int threshold;

    CircuitBreaker(int threshold) { this.threshold = threshold; }

    // 熔断语义:CLOSED 放行并统计连续失败,达到阈值翻到 OPEN 快速失败
    String call(boolean upstreamHealthy) {
        if (state == State.OPEN) {
            return "fast-fail (open)";
        }
        if (upstreamHealthy) {
            failures = 0;
            state = State.CLOSED;
            return "ok";
        }
        if (++failures >= threshold) {
            state = State.OPEN;
            return "opened after " + failures + " failures";
        }
        return "failed " + failures + "/" + threshold;
    }

    public static void main(String[] args) {
        CircuitBreaker breaker = new CircuitBreaker(3);
        System.out.println(breaker.call(false)); // failed 1/3
        System.out.println(breaker.call(false)); // failed 2/3
        System.out.println(breaker.call(false)); // opened after 3 failures
        System.out.println(breaker.call(false)); // fast-fail (open)
        System.out.println(breaker.call(true));  // 仍 fast-fail:不再打到上游
    }
}

Walking through the code

Circuit Breaker State Machine (Java) comes down to the classes CircuitBreaker and State and the function main.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

Signature: public static void main(String[] args)

Key statements

return "opened after " + failures + " failures";
return "failed " + failures + "/" + threshold;
return "fast-fail (open)";

Interactive Tools for This Topic

FAQ

How do you run Circuit Breaker State Machine (Java)?
Just run the file; everything it needs ships with the runtime itself.