Skip to content

API Reference

Frody edited this page Sep 4, 2026 · 1 revision

Complete API Reference & Developer Cheat-Sheet

This document provides a comprehensive technical specification of every interface, class, method, configuration parameter, and runtime state in Fuse, accompanied by concrete code examples.


Table of Contents

  1. Core Interface: CircuitBreaker
  2. Configuration Builder: CircuitBreakerConfig.Builder
  3. Configuration Model: CircuitBreakerConfig
  4. State Model: CircuitBreakerState
  5. Callback Listener: CircuitBreaker.EventListener
  6. Exceptions: CircuitBreakerOpenException

1. Core Interface: CircuitBreaker

Package: io.github.frodygr.circuitbreaker.CircuitBreaker

The primary contract for executing protected actions and inspecting breaker lifecycle.

execute(Supplier<T> supplier)

  • Signature: <T> T execute(Supplier<T> supplier)
  • Description: Executes an operation that returns a value and does not declare checked exceptions. If the circuit is OPEN, throws CircuitBreakerOpenException immediately without invoking the supplier. On successful completion, records a success. If an unhandled exception is thrown and matches recordException, increments the failure counter.
  • Returns: The result value returned by supplier.get().
  • Throws:
    • CircuitBreakerOpenException if the breaker is in OPEN state.
    • RuntimeException any unchecked exception thrown by the underlying supplier.
CircuitBreaker cb = new DefaultCircuitBreaker("inventory-service");

// Protected execution returning a typed object
ProductStock stock = cb.execute(() -> inventoryClient.queryStock("SKU-1049"));

execute(Runnable runnable)

  • Signature: void execute(Runnable runnable)
  • Description: Executes a void operation with no return value and no checked exceptions. Used for notifications, cache eviction, message publishing, or auditing side-effects.
  • Throws:
    • CircuitBreakerOpenException if the breaker is in OPEN state.
    • RuntimeException if the runnable fails.
// Side-effect execution
cb.execute(() -> auditLogPublisher.publishEvent("ORDER_CREATED", orderId));

executeChecked(Callable<T> callable)

  • Signature: <T> T executeChecked(Callable<T> callable) throws Exception
  • Description: Executes an operation that may throw checked exceptions (e.g. IOException, SQLException, InterruptedException). Allows legacy libraries and standard Java I/O clients to run under protection without awkward lambda wrapping.
  • Returns: The value returned by callable.call().
  • Throws:
    • CircuitBreakerOpenException if the breaker is OPEN.
    • Exception any checked or unchecked exception thrown by the callable.
try {
    HttpResponse<String> response = cb.executeChecked(() -> {
        HttpRequest request = HttpRequest.newBuilder(uri).build();
        return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    });
} catch (CircuitBreakerOpenException ex) {
    // Fast-path rejection (zero socket/thread consumption)
} catch (IOException | InterruptedException ex) {
    // Downstream transport failure
}

getState()

  • Signature: CircuitBreakerState getState()
  • Description: Returns the current operational state of the circuit breaker (CLOSED, OPEN, or HALF_OPEN). This method is lock-free, volatile-read safe, and non-blocking.
  • Returns: The current CircuitBreakerState.
CircuitBreakerState currentState = cb.getState();
if (currentState == CircuitBreakerState.OPEN) {
    log.warn("Downstream service is currently isolated.");
}

getName()

  • Signature: String getName()
  • Description: Returns the unique identifier/name assigned to this circuit breaker instance.
  • Returns: Non-null name string.
String identifier = cb.getName(); // e.g. "payment-gateway"

reset()

  • Signature: void reset()
  • Description: Administratively resets the circuit breaker back to CLOSED state, clearing all internal consecutive failure and probe counters to 0. Useful in operations after a downstream deployment, failover, or maintenance window.
// Force immediate operational recovery
cb.reset();

onStateChange(EventListener listener)

  • Signature: void onStateChange(EventListener listener)
  • Description: Registers a thread-safe listener callback to be invoked whenever the circuit transitions between states. Listeners are stored in a lock-free CopyOnWriteArrayList and exceptions thrown by listeners are automatically swallowed to guarantee business transaction safety.
  • Parameters:
    • listener: Implementation of CircuitBreaker.EventListener.
cb.onStateChange((name, fromState, toState) -> {
    System.out.printf("[%s] State changed from %s to %s%n", name, fromState, toState);
});

2. Configuration Builder: CircuitBreakerConfig.Builder

Package: io.github.frodygr.circuitbreaker.CircuitBreakerConfig.Builder

Constructed via CircuitBreakerConfig.builder().

.failureThreshold(int failureThreshold)

  • Parameter: int failureThreshold (must be ≥ 1)
  • Default: 5
  • Description: The number of consecutive recorded failures required in CLOSED state to trip the circuit to OPEN.
  • Throws: IllegalArgumentException if value < 1.
// Trip after 10 consecutive failures
builder.failureThreshold(10);

.successThreshold(int successThreshold)

  • Parameter: int successThreshold (must be ≥ 1)
  • Default: 3
  • Description: The number of consecutive successful probe calls required in HALF_OPEN state to fully restore the circuit back to CLOSED.
  • Throws: IllegalArgumentException if value < 1.
// Require 5 clean probes to consider downstream healthy
builder.successThreshold(5);

.timeout(Duration timeout)

  • Parameter: Duration timeout (non-null, positive duration)
  • Default: Duration.ofSeconds(60)
  • Description: The time window the circuit breaker remains in OPEN before automatically transitioning to HALF_OPEN to test recovery.
  • Throws:
    • NullPointerException if duration is null.
    • IllegalArgumentException if duration is negative or zero.
// Remain OPEN for 20 seconds
builder.timeout(Duration.ofSeconds(20));

.recordException(Predicate<Exception> predicate)

  • Parameter: Predicate<Exception> predicate (non-null)
  • Default: e -> true (all exceptions count as failures)
  • Description: Predicate to filter which exceptions count towards tripping the circuit breaker. Crucial for ignoring client-side 4xx errors, business validation mistakes, or benign conditions.
  • Throws: NullPointerException if predicate is null.
// Only trip on network connection timeouts and 5xx server errors
builder.recordException(ex -> {
    if (ex instanceof IOException || ex instanceof TimeoutException) {
        return true;
    }
    if (ex instanceof RemoteHttpException httpEx) {
        return httpEx.getStatusCode() >= 500;
    }
    return false; // Ignore 4xx validation errors
});

.build()

  • Returns: An immutable, thread-safe CircuitBreakerConfig instance.
CircuitBreakerConfig config = CircuitBreakerConfig.builder()
        .failureThreshold(5)
        .successThreshold(3)
        .timeout(Duration.ofSeconds(30))
        .build();

3. Configuration Model: CircuitBreakerConfig

Package: io.github.frodygr.circuitbreaker.CircuitBreakerConfig

Immutable configuration holding all runtime parameters:

Method Return Type Description
getFailureThreshold() int Returns the configured failure threshold.
getSuccessThreshold() int Returns the configured recovery success threshold.
getTimeout() Duration Returns the duration of the OPEN state.
getRecordExceptionPredicate() Predicate<Exception> Returns the active exception filtering predicate.
static ofDefaults() CircuitBreakerConfig Factory returning default configuration (5 failures, 3 successes, 60s timeout, all exceptions).

4. State Model: CircuitBreakerState

Package: io.github.frodygr.circuitbreaker.CircuitBreakerState

Enumeration representing the state machine lifecycle:

Enum Constant Description Traffic Allowed? Transitions To
CLOSED Normal healthy operation. Yes (All requests executed) OPEN (when failures ≥ failureThreshold)
OPEN Fault isolation / short-circuit active. No (Throws CircuitBreakerOpenException) HALF_OPEN (when elapsed duration ≥ timeout)
HALF_OPEN Recovery testing / probing downstream. Trial Probes CLOSED (when successes ≥ successThreshold)
OPEN (on any probe failure)

5. Callback Listener: CircuitBreaker.EventListener

Package: io.github.frodygr.circuitbreaker.CircuitBreaker.EventListener

Functional interface with signature:

@FunctionalInterface
public interface EventListener {
    void onStateChange(String name, CircuitBreakerState fromState, CircuitBreakerState toState);
}

Full Example: Multi-System Monitoring Listener

circuitBreaker.onStateChange((name, from, to) -> {
    // 1. Structured Logging
    log.info("Circuit Breaker [{}] transitioned: {} -> {}", name, from, to);

    // 2. Metrics Counter
    meterRegistry.counter("cb.transitions", "name", name, "from", from.name(), "to", to.name()).increment();

    // 3. Operational Alerting on OPEN
    if (to == CircuitBreakerState.OPEN) {
        pagerDutyClient.triggerAlert(name + " circuit tripped! Downstream unreachable.");
    }
});

6. Exceptions: CircuitBreakerOpenException

Package: io.github.frodygr.circuitbreaker.CircuitBreakerOpenException

  • Extends: RuntimeException (Unchecked exception)
  • When thrown: When execute(), executeChecked(), or execute(Runnable) is called while the breaker is in OPEN state.
  • Typical usage: Catching explicitly to trigger fallback logic, serve cached snapshots, or return HTTP 503 with a Retry-After header.
try {
    return circuitBreaker.execute(() -> weatherClient.getForecast(city));
} catch (CircuitBreakerOpenException ex) {
    // Fallback: return default cached forecast
    return cachedForecastService.getLatest(city);
}

Clone this wiki locally