在 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>> partitions = partition(data, parallelism);
// 2. 并行执行 Map 阶段
List<completablefuture>> 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>> 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>> parts = new ArrayList(n);
for (int i = 0; i <h2>如何将 Map 结果合并为最终 Reduce 结果</h2>
<p>Reduce 阶段是对 Map 阶段输出的聚合。可以使用 <code>thenCombineAsync</code> 两两合并,或者更简单地,在所有 Map 任务完成后,直接在一个同步或异步上下文中对结果列表进行归约。为了保持非阻塞特性,通常建议在最后一个 <code>thenApply</code> 或 <code>thenAccept</code> 链中完成最终聚合,或者使用 <code>allOf</code> 确保所有前置任务完成后再执行最终的 Reduce 逻辑。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13407" title="Java基础版"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20d79f23518.jpg" alt="Java基础版" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13407" title="Java基础版" class="overflowclass">Java基础版</a>
<p class="overflowclass">编写健壮 Java 代码的基础能力,覆盖空指针防护、相等性判断与基础异常处理。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13407" title="Java基础版" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<p><img src="https://img.php.cn/upload/article/001/242/473/179505885471498.png?x-oss-process=image/resize,p_40" alt="Java CompletableFuture 中 怎么实现 MapReduce"></p>
<pre class="brush:php;toolbar:false;">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>> partitions = partition(data, parallelism);
// 创建 Map 阶段的 Future 列表
List<completablefuture>> 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 a + b);
}
// 获取最终结果
Integer totalSum = reduceFuture.join();
System.out.println("Final Reduced Sum: " + totalSum);
}
private static <t> List<list>> 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>> parts = new ArrayList(n);
for (int i = 0; i <h2>如果 Map 阶段抛出异常,Reduce 阶段会怎样</h2>
<p>如果在 Map 阶段的某个 <code>CompletableFuture</code> 中抛出了未捕获的异常,该 Future 将处于异常状态。当调用 <code>join()</code> 或 <code>get()</code> 时,会抛出 <code>CompletionException</code>。在使用 <code>thenCombineAsync</code> 链接时,如果任一前置 Future 异常,后续的 Combine 操作不会执行,而是直接传播异常。因此,必须通过 <code>exceptionally</code> 或 <code>handle</code> 方法来处理潜在的错误,否则整个流水线会中断。</p></list></t></list></t></integer></integer></completablefuture></list></integer>
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










