java 的 completablefuture 本身没有内置背压机制,但可以通过限制并发度来实现流量控制。具体做法是使用自定义的 executorservice 包装 forkjoinpool.commonpool() 或创建固定大小的线程池,并在提交任务时利用 semaphore 进行信号量控制,从而限制同时运行的任务数量。

如何限制 CompletableFuture 的并发执行数
通过结合 ExecutorService 和 Semaphore 可以精确控制并发度。创建一个固定大小的线程池作为执行器,并使用一个初始许可数为最大并发数的信号量。在提交每个 CompletableFuture 任务前获取信号量许可,任务完成后释放许可,以此防止系统过载。

import java.util.concurrent.*;
public class BackpressureExample {
private static final int MAX_CONCURRENCY = 5;
private static final Semaphore semaphore = new Semaphore(MAX_CONCURRENCY);
private static final ExecutorService executor = Executors.newFixedThreadPool(MAX_CONCURRENCY);
public static void main(String[] args) throws Exception {
for (int i = 0; i {
try {
System.out.println("Task " + taskId + " started at " + Thread.currentThread().getName());
Thread.sleep(1000); // 模拟耗时操作
return taskId * 2;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
// 任务结束后释放许可
semaphore.release();
}
}, executor).thenAccept(result -> {
System.out.println("Task " + taskId + " finished with result: " + result);
});
}
// 保持主线程运行以观察结果
Thread.sleep(15000);
executor.shutdown();
}
}
上述代码中,MAX_CONCURRENCY 设置为 5,意味着最多只有 5 个任务能同时执行。当 10 个任务提交时,前 5 个立即开始,后 5 个会阻塞在 semaphore.acquire() 处,直到前面的任务完成并调用 semaphore.release()。这种模式有效防止了资源耗尽。
如何处理 CompletableFuture 中的异常与背压恢复
在使用背压机制时,必须处理任务执行过程中可能出现的异常,以避免信号量泄漏或程序挂起。通过 exceptionally 方法捕获异常,确保即使任务失败也能正确释放信号量许可,维持系统的稳定性。
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。

import java.util.concurrent.*;
public class ExceptionHandlingBackpressure {
private static final int MAX_CONCURRENCY = 3;
private static final Semaphore semaphore = new Semaphore(MAX_CONCURRENCY);
private static final ExecutorService executor = Executors.newFixedThreadPool(MAX_CONCURRENCY);
public static void main(String[] args) throws Exception {
for (int i = 0; i {
if (taskId == 2) {
throw new RuntimeException("Simulated failure in task " + taskId);
}
return taskId;
}, executor)
.thenAccept(result -> System.out.println("Success: " + result))
.exceptionally(ex -> {
System.err.println("Error: " + ex.getMessage());
return null;
})
.whenComplete((result, ex) -> {
// 无论成功还是失败,都释放信号量
semaphore.release();
});
}
Thread.sleep(10000);
executor.shutdown();
}
}
在这个示例中,taskId 为 2 的任务会抛出异常。exceptionally 块处理了异常并返回 null,而 whenComplete 确保了信号量的释放。这保证了即使发生错误,背压机制依然有效,不会导致后续任务永久阻塞。
基于信号量许可获取超时的具体行为是什么
当所有信号量许可都被占用且没有可用许可时,acquire() 方法会无限期阻塞。如果需要避免无限等待,可以使用带超时的 tryAcquire(long timeout, TimeUnit unit) 方法。如果超时时间内无法获取许可,该方法返回 false,允许调用者采取降级策略,如丢弃任务或重试。
import java.util.concurrent.*;
public class TimeoutBackpressure {
private static final int MAX_CONCURRENCY = 2;
private static final Semaphore semaphore = new Semaphore(MAX_CONCURRENCY);
private static final ExecutorService executor = Executors.newFixedThreadPool(MAX_CONCURRENCY);
public static void main(String[] args) throws Exception {
for (int i = 0; i {
System.out.println("Task " + taskId + " executed");
return taskId;
}, executor).thenAccept(res -> {
semaphore.release();
});
} else {
System.out.println("Task " + taskId + " rejected due to backpressure");
}
}
Thread.sleep(10000);
executor.shutdown();
}
}
此代码展示了使用 tryAcquire 的行为。如果 2 秒内无法获取许可,任务将被拒绝并打印相应消息,而不是无限期等待。这提供了一种更灵活的背压处理方式,适用于对延迟敏感的场景。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










