Virtual Threads Bounded By Semaphore

Bound virtual thread concurrency with a Semaphore: tasks fan out cheaply while the permit count caps simultaneous in-flight downstream calls.

JavaResilience

Code

snippet
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class BoundedFanOut {

    public static void main(String[] args) throws Exception {
        // 虚拟线程便宜到可以海量创建:真正的限流闸门交给 Semaphore
        Semaphore permits = new Semaphore(2);
        AtomicInteger inFlight = new AtomicInteger();
        AtomicInteger peak = new AtomicInteger();
        AtomicInteger completed = new AtomicInteger();

        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 6; i++) {
                executor.submit(() -> {
                    permits.acquire();
                    try {
                        int now = inFlight.incrementAndGet();
                        peak.accumulateAndGet(now, Math::max);
                        Thread.sleep(Duration.ofMillis(50)); // 模拟一次下游调用
                    } finally {
                        inFlight.decrementAndGet();
                        permits.release();
                    }
                    completed.incrementAndGet();
                    return null;
                });
            }
        } // close() 阻塞等待全部任务结束
        System.out.println("completed = " + completed.get());
        System.out.println("peak concurrency = " + peak.get());
    }
}

A look at the moving parts

Under the hood: the class BoundedFanOut.

Iteration happens inside for (int i = 0; i < 6; i++) — everything outside it runs once. Resources live in the try header, so closing is compiler-generated and exception-safe.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Putting it to use

The run prints completed =, peak concurrency = — each prefix names the step that produced it.

Core lines

Thread.sleep(Duration.ofMillis(50)); // 模拟一次下游调用
} finally {
inFlight.decrementAndGet();

Interactive Tools for This Topic

FAQ

What does Virtual Threads Bounded By Semaphore print when run?
Run it as a complete program — the output lines carry labels such as `completed =`, `peak concurrency =`.