← 中文资源

简体中文版本

信号量限流虚拟线程

虚拟线程创建便宜但不应无限放大下游压力:用 Semaphore 把同时在途的调用数压到许可数以内,并用峰值计数验证限流确实生效。

阅读英文原文

实现说明

真正干活的是类 BoundedFanOut,其余都是接线。 for (int i = 0; i < 6; i++) 是唯一的迭代点——其余代码顺序执行一遍。资源声明在 try-with-resources 头部,任何退出路径都会自动关闭;方法里的 finally 块另行执行自己的清理。

使用要点

  • 跑完文件,输出里会留下标记——completed =、peak concurrency =。

常见问题

运行「信号量限流虚拟线程」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 completed =、peak concurrency = 标签标明各步骤。

核心语句

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

代码示例

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());
    }
}