// Created on savesnippets.com · https://savesnippets.com/3uwEg5QkaaPTA6 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 } }