java
60 lines · 7 steps
How a circuit breaker guards failing calls
A three-state machine that stops hammering a failing dependency and probes for recovery before letting traffic back through.
Explained by
highlit
1public final class CircuitBreaker {
2
3 private enum State { CLOSED, OPEN, HALF_OPEN }
4
5 private final int failureThreshold;
6 private final int successThreshold;
7 private final long openDurationMillis;
8
9 private volatile State state = State.CLOSED;
10 private final AtomicInteger failureCount = new AtomicInteger();
11 private final AtomicInteger successCount = new AtomicInteger();
12 private volatile long openedAt = 0L;
13
14 public CircuitBreaker(int failureThreshold, int successThreshold, Duration openDuration) {
15 this.failureThreshold = failureThreshold;
16 this.successThreshold = successThreshold;
17 this.openDurationMillis = openDuration.toMillis();
18 }
19
20 public <T> T execute(Supplier<T> action) throws Exception {
21 if (state == State.OPEN) {
22 if (System.currentTimeMillis() - openedAt < openDurationMillis) {
23 throw new CircuitOpenException("circuit is open");
24 }
25 transitionTo(State.HALF_OPEN);
26 }
27
28 try {
29 T result = action.get();
30 onSuccess();
31 return result;
32 } catch (RuntimeException ex) {
33 onFailure();
34 throw ex;
35 }
36 }
37
38 private synchronized void onSuccess() {
39 if (state == State.HALF_OPEN) {
40 if (successCount.incrementAndGet() >= successThreshold) {
41 transitionTo(State.CLOSED);
42 }
43 } else {
44 failureCount.set(0);
45 }
46 }
47
48 private synchronized void onFailure() {
49 if (state == State.HALF_OPEN || failureCount.incrementAndGet() >= failureThreshold) {
50 openedAt = System.currentTimeMillis();
51 transitionTo(State.OPEN);
52 }
53 }
54
55 private void transitionTo(State next) {
56 state = next;
57 failureCount.set(0);
58 successCount.set(0);
59 }
60}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A circuit breaker trades occasional fast failures for protecting a struggling dependency from a flood of doomed requests.
- 2The HALF_OPEN state lets exactly a probe of traffic through so recovery is detected without fully reopening the floodgates.
- 3Marking mutable state volatile and confining transitions to synchronized methods keeps the machine consistent under concurrent calls.
Related explainers
go
package server import ( "net/http"
Rate limiting HTTP handlers with a token bucket
rate-limiting
token-bucket
middleware
Advanced
7 steps
rust
use std::collections::HashMap; #[derive(Clone, Copy, PartialEq)] enum Color {
Detecting cycles with three-color DFS in Rust
graph-algorithms
cycle-detection
depth-first-search
Intermediate
9 steps
java
public Map<Long, CustomerDto> indexByCustomerId(List<CustomerDto> customers) { return customers.stream() .collect(Collectors.toMap( CustomerDto::getId,
Building maps from lists with Collectors.toMap
streams
collectors
maps
Intermediate
5 steps
php
<?php namespace App\Jobs;
Debouncing a Laravel shipping-rate job
queues
debouncing
atomic-locks
Advanced
9 steps
java
@Service public class InventoryService { private final RestClient warehouseClient;
Bulkhead-protected HTTP calls in Spring
bulkhead
resilience
fallback
Intermediate
7 steps
java
@Configuration public class DataSourceLoggingConfig { @Bean
Wrapping a Spring DataSource for query tracing
proxy pattern
observability
data source
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-circuit-breaker-guards-failing-calls-explained-java-2e0c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.