
本文介绍如何将单线程顺序处理 10,000 条记录的 ArrayList 改造成多线程并行处理,通过 CompletableFuture + 线程池实现 REST 批量调用,显著提升吞吐量,同时确保只读场景下的线程安全性。
本文介绍如何将单线程顺序处理 10,000 条记录的 arraylist 改造成多线程并行处理,通过 `completablefuture` + 线程池实现 rest 批量调用,显著提升吞吐量,同时确保只读场景下的线程安全性。
在 Java 中,若一个 static ArrayList 仅被多个线程并发读取(无任何写操作),则无需额外同步——因为 ArrayList 的读操作(如 get()、subList())本身是线程安全的(前提是结构未被修改)。本例中,原始数据一次性初始化后不再变更,因此可放心将不同批次的子列表(records.subList(startIndex, endIndex))分发给多个线程并行处理。
以下是一个生产就绪的多线程批量处理方案,使用 CompletableFuture 实现异步非阻塞执行,并通过固定大小线程池控制资源消耗:
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
public class BatchRestProcessor {
// 假设这是初始化完成的静态只读数据源
private static final List<String> STATIC_RECORDS = initializeRecords();
private static List<String> initializeRecords() {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10_000; i++) {
list.add("record-" + i);
}
return Collections.unmodifiableList(list); // 强制只读,防止意外修改
}
public static void main(String[] args) throws InterruptedException {
int batchSize = 100;
int threadPoolSize = Math.min(16, (int) Math.ceil((double) STATIC_RECORDS.size() / batchSize));
ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < STATIC_RECORDS.size(); i += batchSize) {
int start = i;
int end = Math.min(i + batchSize, STATIC_RECORDS.size());
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
List<String> batch = STATIC_RECORDS.subList(start, end);
processBatch(batch); // 模拟 REST 调用(建议使用 WebClient 或 OkHttp 异步客户端)
}, executor);
futures.add(future);
}
// 等待所有批次完成(支持超时控制更佳)
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.orTimeout(20, TimeUnit.MINUTES)
.join();
System.out.println("✅ All batches processed successfully.");
} catch (CompletionException e) {
System.err.println("❌ Batch processing failed: " + e.getCause());
throw e;
} finally {
executor.shutdown();
if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
}
}
private static void processBatch(List<String> batch) {
// ✅ 安全:batch 是不可变视图,且 STATIC_RECORDS 本身不可修改
// ⚠️ 注意:实际 REST 调用应使用真正的异步 HTTP 客户端(如 Spring WebClient、OkHttp Call.enqueue)
// 示例(伪代码):
// webClient.post()
// .uri("/api/batch")
// .bodyValue(batch)
// .retrieve()
// .toBodilessEntity()
// .block(); // ❌ 避免在 compute-intensive 线程中 block;应链式 await 或用 Mono.then()
System.out.printf("[Thread %s] Processing batch of %d items%n",
Thread.currentThread().getName(), batch.size());
// 模拟网络延迟(勿在生产中用 Thread.sleep)
try {
Thread.sleep(50); // 替换为真实异步 I/O
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}关键设计说明与最佳实践:
- ✅ 线程安全前提:
STATIC_RECORDS使用Collections.unmodifiableList()封装,彻底杜绝运行时修改风险;subList()返回的是原列表的不可修改视图,不涉及共享状态写入。 - ⚙️ 线程池调优:线程数不宜盲目设高。I/O 密集型任务(如 REST 调用)推荐
2 × CPU核心数 ~ 4 × CPU核心数;本例采用动态计算(最多 16 线程),兼顾并发度与上下文切换开销。 - ? 异步 I/O 优先:示例中
processBatch内部仍含sleep仅为演示;真实场景务必替换为非阻塞 HTTP 客户端(如 Spring WebFlux 的WebClient),避免线程被空等阻塞,最大化吞吐。 - ? 异常处理强化:使用
orTimeout()防止某批次卡死拖垮整体;CompletableFuture.allOf()不传播子 future 异常,需配合handle()或exceptionally()做细粒度错误日志/重试。 - ? 内存友好:
subList()不复制数据,零内存开销;若后续需深拷贝或转换格式(如转 JSON),应在子线程内按需处理,避免主线程压力。
通过该方案,原本 15 分钟的单线程串行任务,在合理配置下可压缩至 1–3 分钟(取决于后端接口响应时间与网络带宽),性能提升可达 5× 以上,且代码清晰、健壮、易于监控与扩展。

















