使用限流机制保护系统,核心做法是在提交异步任务前通过信号量(semaphore)或自定义线程池进行流量控制。具体实现时,调用 acquire() 获取许可,在 completablefuture 的链式调用中执行业务逻辑,并在 finally 块中确保调用 release() 释放许可。这样可以在高并发场景下限制同时运行的任务数量,防止系统过载。

如何基于 Semaphore 实现非阻塞限流
利用 Semaphore 的 tryAcquire() 方法可以实现非阻塞限流。当可用许可不足时,直接返回失败或抛出异常,而不是让线程挂起等待。这种方式适合对响应时间敏感的场景,能够快速拒绝超额请求。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;
public class NonBlockingRateLimiter {
private final Semaphore semaphore;
public NonBlockingRateLimiter(int permits) {
this.semaphore = new Semaphore(permits);
}
public CompletableFuture<string> executeTask(String taskId) {
if (semaphore.tryAcquire()) {
return CompletableFuture.supplyAsync(() -> {
try {
// 模拟业务处理
Thread.sleep(100);
return "Task " + taskId + " completed";
} finally {
semaphore.release();
}
});
} else {
return CompletableFuture.failedFuture(new RuntimeException("System busy, try again later"));
}
}
}</string>
上述代码展示了非阻塞限流的实现。当 tryAcquire() 返回 false 时,立即返回一个失败的 CompletableFuture。这避免了线程在信号量上阻塞,提高了系统的吞吐量。预期结果是:当并发请求超过许可数时,多余请求会迅速失败,而不会导致线程堆积。
如何结合线程池优化限流效果
将 Semaphore 与自定义 ExecutorService 结合,可以更精细地控制资源消耗。通过限制线程池的核心线程数和队列大小,配合信号量的许可数,可以形成双重保护。这种组合方式适合需要平衡 CPU 和内存资源的场景。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

import java.util.concurrent.*;
public class OptimizedRateLimiter {
private final Semaphore semaphore;
private final ExecutorService executor;
public OptimizedRateLimiter(int permits, int poolSize) {
this.semaphore = new Semaphore(permits);
this.executor = new ThreadPoolExecutor(
poolSize, poolSize, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()
);
}
public CompletableFuture<string> executeTask(String taskId) {
return CompletableFuture.supplyAsync(() -> {
try {
semaphore.acquire();
// 模拟业务处理
Thread.sleep(50);
return "Task " + taskId + " processed";
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Task interrupted", e);
} finally {
semaphore.release();
}
}, executor);
}
public void shutdown() {
executor.shutdown();
}
}</string>
该方案通过 ThreadPoolExecutor 限制并发线程数,同时用 Semaphore 进一步限制实际执行业务逻辑的任务数。预期结果是:即使有大量任务提交,也只有不超过许可数的任务能真正执行,其余任务会在信号量处等待或被拒绝。这种设计能有效防止系统资源耗尽。
当信号量许可耗尽时 CompletableFuture 的行为是什么
当信号量许可耗尽且使用 acquire() 时,提交任务的线程会被阻塞,直到有许可释放。如果使用 tryAcquire() 失败,则 CompletableFuture 会立即进入失败状态。这种行为差异决定了系统在高负载下的表现:阻塞会导致线程等待,而快速失败则能保持系统响应性。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










