Semaphore Rate Limiting Permits

Cap concurrent work with a counting Semaphore: tryAcquire rejects overflow immediately and release frees the slot in a finally block.

JavaResilience

Code

snippet
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class ApiGateway {

    public static void main(String[] args) throws InterruptedException {
        // rate limit: 3 permits = 最多 3 个请求同时进入处理区
        Semaphore slots = new Semaphore(3);

        try (ExecutorService pool = Executors.newFixedThreadPool(6)) {
            for (int i = 1; i <= 6; i++) {
                String request = "req-" + i;
                pool.submit(() -> {
                    boolean admitted = false;
                    try {
                        // 拿不到许可立刻拒绝,而不是无限排队
                        if (slots.tryAcquire()) {
                            admitted = true;
                            System.out.println(request + " admitted, available: " + slots.availablePermits());
                            Thread.sleep(300); // 模拟下游调用
                        } else {
                            System.out.println(request + " rejected");
                        }
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        if (admitted) {
                            slots.release(); // 只有成功拿到许可才归还
                        }
                    }
                });
            }
        }
    }
}

How it works

Count the class ApiGateway as the entire surface area of Semaphore Rate Limiting Permits.

Repetition is confined to for (int i = 1; i <= 6; i++) — the rest of the file is straight-line. Resources are declared in a try-with-resources header, so they close on every exit path; the finally block in this method runs separately for its own cleanup.

Core lines

Thread.currentThread().interrupt();
Thread.sleep(300); // 模拟下游调用
} else {
System.out.println(request + " rejected");

Interactive Tools for This Topic

FAQ

How do you run Semaphore Rate Limiting Permits?
The file is self-contained: run it directly, no dependencies to install beforehand.