在 java 中实现 mapreduce,核心思路是利用 completablefuture 的并行能力将任务拆分为独立的 map 阶段和 reduce 阶段。具体做法是:使用 forkjoinpool.commonpool() 提交多个异步任务处理输入数据的子集(map),收集所有结果后,通过 thencombineasync 或 allof 等待它们完成,最后在主线程或另一个异步任务中进行聚合(reduce)。

如何并行执行 Map 阶段并收集结果
要实现 Map 阶段的并行化,需要将输入数据切分,为每个切片创建一个 CompletableFuture。这些任务在公共 Fork-Join 池中并发执行,互不阻塞。关键在于使用 supplyAsync 来启动任务,并确保每个任务返回其局部计算结果。当所有 Map 任务都完成后,才能进入下一步。

import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
public class CompletableFutureMapReduce {
public static void main(String[] args) throws Exception {
List<Integer> data = List.of(1, 2, 3, 4, 5, 6, 7, 8);
int parallelism = 4;
// 1. 拆分数据
List<List<Integer>> partitions = partition(data, parallelism);
// 2. 并行执行 Map 阶段
List<CompletableFuture<Integer>> futures = new ArrayList<>();
for (List<Integer> part : partitions) {
futures.add(CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " processing " + part);
return part.stream().mapToInt(i -> i * 2).sum();
}));
}
// 3. 等待所有 Map 完成并获取结果
Integer[] mapResults = futures.stream()
.map(CompletableFuture::join)
.toArray(Integer[]::new);
System.out.println("Map Results: " + java.util.Arrays.toString(mapResults));
}
private static <T> List<List<T>> partition(List<T> list, int n) {
int size = list.size();
if (size == 0) return List.of();
int chunkSize = (int) Math.ceil((double) size / n);
List<List<T>> parts = new ArrayList<>(n);
for (int i = 0; i < size; i += chunkSize) {
parts.add(list.subList(i, Math.min(i + chunkSize, size)));
}
return parts;
}
}
如何将 Map 结果合并为最终 Reduce 结果
Reduce 阶段是对 Map 阶段输出的聚合。可以使用 thenCombineAsync 两两合并,或者更简单地,在所有 Map 任务完成后,直接在一个同步或异步上下文中对结果列表进行归约。为了保持非阻塞特性,通常建议在最后一个 thenApply 或 thenAccept 链中完成最终聚合,或者使用 allOf 确保所有前置任务完成后再执行最终的 Reduce 逻辑。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
public class CompletableFutureFullMapReduce {
public static void main(String[] args) throws Exception {
List<Integer> data = List.of(1, 2, 3, 4, 5, 6, 7, 8);
int parallelism = 4;
List<List<Integer>> partitions = partition(data, parallelism);
// 创建 Map 阶段的 Future 列表
List<CompletableFuture<Integer>> mapFutures = new ArrayList<>();
for (List<Integer> part : partitions) {
mapFutures.add(CompletableFuture.supplyAsync(() -> {
return part.stream().mapToInt(i -> i * 2).sum();
}));
}
// 构建 Reduce 阶段:将所有 Map 结果合并
CompletableFuture<Integer> reduceFuture = mapFutures.get(0);
for (int i = 1; i < mapFutures.size(); i++) {
final int index = i;
reduceFuture = reduceFuture.thenCombineAsync(mapFutures.get(index), (a, b) -> a + b);
}
// 获取最终结果
Integer totalSum = reduceFuture.join();
System.out.println("Final Reduced Sum: " + totalSum);
}
private static <T> List<List<T>> partition(List<T> list, int n) {
int size = list.size();
if (size == 0) return List.of();
int chunkSize = (int) Math.ceil((double) size / n);
List<List<T>> parts = new ArrayList<>(n);
for (int i = 0; i < size; i += chunkSize) {
parts.add(list.subList(i, Math.min(i + chunkSize, size)));
}
return parts;
}
}
如果 Map 阶段抛出异常,Reduce 阶段会怎样
如果在 Map 阶段的某个 CompletableFuture 中抛出了未捕获的异常,该 Future 将处于异常状态。当调用 join() 或 get() 时,会抛出 CompletionException。在使用 thenCombineAsync 链接时,如果任一前置 Future 异常,后续的 Combine 操作不会执行,而是直接传播异常。因此,必须通过 exceptionally 或 handle 方法来处理潜在的错误,否则整个流水线会中断。


















