← 中文资源

简体中文版本

ConcurrentHashMap 并行 search 与 reduce

search 找到首个命中即返回,reduce 把各条目抽值后归并求和;parallelismThreshold 之下串行、之上才拆分到 ForkJoinPool 公共池。

阅读英文原文

实现说明

逻辑集中在类 ParallelScan和函数 main里。

使用要点

  • 每一步打印都带着自己的标签:shortage:、total units:。

常见问题

运行「ConcurrentHashMap 并行 search 与 reduce」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 shortage:、total units: 这类标签。

核心语句

int totalUnits = stock.reduce(2, (item, qty) -> qty, Integer::sum);

代码示例

import java.util.concurrent.ConcurrentHashMap;

public class ParallelScan {

    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>();
        stock.put("gpu", 3);
        stock.put("cpu", 12);
        stock.put("ssd", 45);
        stock.put("ram", 8);

        // search: returns as soon as any entry matches; only gpu is below 5, so the outcome is settled
        // with several matches it returns whichever is scanned first (parallel scan order is unspecified)
        String shortage = stock.search(4, (item, qty) -> qty < 5 ? item : null);
        System.out.println("shortage: " + shortage);

        // reduce: the transformer extracts values, the reducer merges them; parallelism only kicks in past the threshold
        int totalUnits = stock.reduce(2, (item, qty) -> qty, Integer::sum);
        System.out.println("total units: " + totalUnits);

        // threshold semantics: at or below it everything runs serially, above it the work splits onto the common ForkJoinPool
        // pass Long.MAX_VALUE to stay fully serial and spare small maps the divide-and-conquer overhead
    }
}