-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference
This document provides a comprehensive technical specification of every interface, class, method, configuration parameter, and runtime state in Fuse, accompanied by concrete code examples.
- Core Interface:
CircuitBreaker - Configuration Builder:
CircuitBreakerConfig.Builder - Configuration Model:
CircuitBreakerConfig - State Model:
CircuitBreakerState - Callback Listener:
CircuitBreaker.EventListener - Exceptions:
CircuitBreakerOpenException
Package: io.github.frodygr.circuitbreaker.CircuitBreaker
The primary contract for executing protected actions and inspecting breaker lifecycle.
-
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, throwsCircuitBreakerOpenExceptionimmediately without invoking the supplier. On successful completion, records a success. If an unhandled exception is thrown and matchesrecordException, increments the failure counter. -
Returns: The result value returned by
supplier.get(). -
Throws:
-
CircuitBreakerOpenExceptionif the breaker is inOPENstate. -
RuntimeExceptionany 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"));-
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:
-
CircuitBreakerOpenExceptionif the breaker is inOPENstate. -
RuntimeExceptionif the runnable fails.
-
// Side-effect execution
cb.execute(() -> auditLogPublisher.publishEvent("ORDER_CREATED", orderId));-
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:
-
CircuitBreakerOpenExceptionif the breaker isOPEN. -
Exceptionany 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
}-
Signature:
CircuitBreakerState getState() -
Description: Returns the current operational state of the circuit breaker (
CLOSED,OPEN, orHALF_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.");
}-
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"-
Signature:
void reset() -
Description: Administratively resets the circuit breaker back to
CLOSEDstate, clearing all internal consecutive failure and probe counters to0. Useful in operations after a downstream deployment, failover, or maintenance window.
// Force immediate operational recovery
cb.reset();-
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
CopyOnWriteArrayListand exceptions thrown by listeners are automatically swallowed to guarantee business transaction safety. -
Parameters:
-
listener: Implementation ofCircuitBreaker.EventListener.
-
cb.onStateChange((name, fromState, toState) -> {
System.out.printf("[%s] State changed from %s to %s%n", name, fromState, toState);
});Package: io.github.frodygr.circuitbreaker.CircuitBreakerConfig.Builder
Constructed via CircuitBreakerConfig.builder().
-
Parameter:
int failureThreshold(must be ≥ 1) -
Default:
5 -
Description: The number of consecutive recorded failures required in
CLOSEDstate to trip the circuit toOPEN. -
Throws:
IllegalArgumentExceptionif value < 1.
// Trip after 10 consecutive failures
builder.failureThreshold(10);-
Parameter:
int successThreshold(must be ≥ 1) -
Default:
3 -
Description: The number of consecutive successful probe calls required in
HALF_OPENstate to fully restore the circuit back toCLOSED. -
Throws:
IllegalArgumentExceptionif value < 1.
// Require 5 clean probes to consider downstream healthy
builder.successThreshold(5);-
Parameter:
Duration timeout(non-null, positive duration) -
Default:
Duration.ofSeconds(60) -
Description: The time window the circuit breaker remains in
OPENbefore automatically transitioning toHALF_OPENto test recovery. -
Throws:
-
NullPointerExceptionif duration is null. -
IllegalArgumentExceptionif duration is negative or zero.
-
// Remain OPEN for 20 seconds
builder.timeout(Duration.ofSeconds(20));-
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:
NullPointerExceptionif 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
});-
Returns: An immutable, thread-safe
CircuitBreakerConfiginstance.
CircuitBreakerConfig config = CircuitBreakerConfig.builder()
.failureThreshold(5)
.successThreshold(3)
.timeout(Duration.ofSeconds(30))
.build();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). |
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) |
Package: io.github.frodygr.circuitbreaker.CircuitBreaker.EventListener
Functional interface with signature:
@FunctionalInterface
public interface EventListener {
void onStateChange(String name, CircuitBreakerState fromState, CircuitBreakerState toState);
}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.");
}
});Package: io.github.frodygr.circuitbreaker.CircuitBreakerOpenException
-
Extends:
RuntimeException(Unchecked exception) -
When thrown: When
execute(),executeChecked(), orexecute(Runnable)is called while the breaker is inOPENstate. -
Typical usage: Catching explicitly to trigger fallback logic, serve cached snapshots, or return HTTP 503 with a
Retry-Afterheader.
try {
return circuitBreaker.execute(() -> weatherClient.getForecast(city));
} catch (CircuitBreakerOpenException ex) {
// Fallback: return default cached forecast
return cachedForecastService.getLatest(city);
}Fuse • Zero-Dependency Circuit Breaker for Java 17+ • Licensed under Apache-2.0