Java

Semaphore — Bounded Concurrency

admin by @admin ADMIN
4d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Limit how many threads can enter a critical section. `acquire()` blocks until a permit is available; `release()` returns one. Use for rate limits, connection pools, or any "max N at a time" pattern.
Java
Raw
import java.util.concurrent.*;

class Demo {
    // Allow at most 3 concurrent API calls
    final Semaphore apiLimit = new Semaphore(3);

    void callApi(int id) {
        try {
            apiLimit.acquire();                      // blocks if 3 already in flight
            System.out.println("[" + id + "] calling API");
            Thread.sleep(500);                       // pretend HTTP work
            System.out.println("[" + id + "] done");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            apiLimit.release();                      // always release in finally
        }
    }

    void example() throws Exception {
        try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10; i++) {
                int id = i;
                pool.submit(() -> callApi(id));
            }
        }
        // Observe — only 3 "calling API" prints active at once
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.