DefaultCircuitBreaker

class DefaultCircuitBreaker(config: CircuitBreakerConfig, timeSource: TimeSource = SystemTimeSource, onStateChanged: (CircuitState, CircuitState) -> Unit = { _, _ -> }) : CircuitBreaker

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.

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 Mutex is used to ensure atomic state transitions.

  • State Updates: All state modifications are protected by a Mutex.

  • User Code Execution: The provided block of code is always executed outside the lock to prevent holding the mutex for an extended period.

Parameters

config

The circuit breaker configuration.

timeSource

Source of current time for open/half-open timeouts; defaults to SystemTimeSource.

onStateChanged

Callback invoked on state transition (newState, oldState); used for telemetry.

Constructors

Link copied to clipboard
constructor(config: CircuitBreakerConfig, timeSource: TimeSource = SystemTimeSource, onStateChanged: (CircuitState, CircuitState) -> Unit = { _, _ -> })

Properties

Link copied to clipboard
open override val state: StateFlow<CircuitState>

The current state of the circuit: CircuitState.CLOSED, CircuitState.OPEN, or CircuitState.HALF_OPEN.

Functions

Link copied to clipboard
open suspend override fun <T> execute(block: suspend () -> T): T

Executes block if the circuit allows it; otherwise throws CircuitBreakerOpenException.

Link copied to clipboard
open override fun snapshot(): CircuitBreakerSnapshot

Returns a point-in-time snapshot of the circuit breaker state.