Resilience

resilience3Bulkhead

Path
pkg18resiliencepatterns/resilience3Bulkhead.java
Package
pkg18resiliencepatterns
Study order
3
Run
Single-file source launch
Command
java pkg18resiliencepatterns/resilience3Bulkhead.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg18resiliencepatterns/resilience3Bulkhead.java
1package pkg18resiliencepatterns;2 3import java.util.concurrent.ExecutorService;4import java.util.concurrent.Executors;5import java.util.concurrent.Semaphore;6import java.util.concurrent.TimeUnit;7 8/*9 * resilience3Bulkhead.java10 * ------------------------11 * Bulkhead: isolate resources so one slow/failing area cannot exhaust the pool.12 *13 * DEFINITION:14 *   Like ship bulkheads that contain flooding. Limit concurrent calls to a15 *   dependency (semaphore/thread pool) so other parts of the system stay healthy.16 *17 * KEY POINTS:18 *   - Separate pools for DB, HTTP, cache — don't share one giant pool.19 *   - Reject or queue when bulkhead is full (fail fast vs wait).20 *   - Pair with circuit breaker for defense in depth.21 */22public class resilience3Bulkhead {23 24    static class Bulkhead {25        private final Semaphore permits;26 27        Bulkhead(int maxConcurrent) { permits = new Semaphore(maxConcurrent); }28 29        void run(Runnable task) throws InterruptedException {30            if (!permits.tryAcquire(100, TimeUnit.MILLISECONDS)) {31                throw new RuntimeException("Bulkhead full — rejected");32            }33            try {34                task.run();35            } finally {36                permits.release();37            }38        }39    }40 41    public static void main(String[] args) throws InterruptedException {42        Bulkhead dbBulkhead = new Bulkhead(2); // only 2 concurrent DB calls43        ExecutorService exec = Executors.newFixedThreadPool(5);44 45        for (int i = 0; i < 5; i++) {46            int id = i;47            exec.submit(() -> {48                try {49                    dbBulkhead.run(() -> {50                        System.out.println("  task " + id + " in bulkhead");51                        try { Thread.sleep(300); } catch (InterruptedException e) {52                            Thread.currentThread().interrupt();53                        }54                    });55                } catch (Exception e) {56                    System.out.println("  task " + id + " rejected: " + e.getMessage());57                }58            });59        }60        exec.shutdown();61        exec.awaitTermination(5, TimeUnit.SECONDS);62    }63}