DefaultCircuitBreaker
A default, thread-safe implementation of the CircuitBreaker interface.
This class protects a system from failures by stopping the execution of operations when a certain failure threshold is reached. It follows a state machine pattern with three states: CircuitState.CLOSED, CircuitState.OPEN, and CircuitState.HALF_OPEN.
CircuitState.CLOSED: The default state. All calls are executed. If the number of failures exceeds the configured
failureThreshold, the state transitions to CircuitState.OPEN.CircuitState.OPEN: Calls are immediately rejected with a CircuitBreakerOpenException without attempting to execute them. After a configured
timeout, the state transitions to CircuitState.HALF_OPEN.CircuitState.HALF_OPEN: A limited number of calls (configured by
halfOpenMaxCalls) are allowed to execute to test if the underlying system has recovered. If these calls succeed (up to thesuccessThreshold), the circuit transitions back to CircuitState.CLOSED. If any of these test calls fail, it transitions back to CircuitState.OPEN.
Thread Safety and Concurrency
This implementation is designed to be highly concurrent and thread-safe.
State Checks: A fast-path check is used for the common CircuitState.CLOSED state, which avoids locking and allows maximum concurrency. For CircuitState.OPEN and CircuitState.HALF_OPEN states, a
Mutexis used to ensure atomic state transitions.State Updates: All state modifications are protected by a
Mutex.User Code Execution: The provided
blockof code is always executed outside the lock to prevent holding the mutex for an extended period.
Parameters
The circuit breaker configuration.
Source of current time for open/half-open timeouts; defaults to SystemTimeSource.
Callback invoked on state transition (newState, oldState); used for telemetry.
Constructors
Properties
The current state of the circuit: CircuitState.CLOSED, CircuitState.OPEN, or CircuitState.HALF_OPEN.