gpt4 book ai didi

java - 为什么我的收集器方法没有并行处理数据?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:13 24 4
gpt4 key购买 nike

Suppose, however, that the result container used in this reduction was a concurrently modifiable collection -- such as a ConcurrentHashMap. In that case, the parallel invocations of the accumulator could actually deposit their results concurrently into the same shared result container, eliminating the need for the combiner to merge distinct result containers. This potentially provides a boost to the parallel execution performance. We call this a concurrent reduction.

还有

A Collector that supports concurrent reduction is marked with the Collector.Characteristics.CONCURRENT characteristic. However, a concurrent collection also has a downside. If multiple threads are depositing results concurrently into a shared container, the order in which results are deposited is non-deterministic.

来自 document

这意味着 collect 方法与供应商(并发线程安全)应该有 Collector.Characteristics.CONCURRENT。因此不应维持任何秩序。

但是我的代码

List<Employee> li=Arrays.asList(Employee.emparr());
System.out.println("printing concurrent result "+li.stream().parallel().unordered().map(s->s.getName()).collect(() -> new ConcurrentLinkedQueue<>(),
(c, e) -> c.add(e.toString()),
(c1, c2) -> c1.addAll(c2))
.toString());

总是按照遇到的顺序打印结果。这是否意味着我的 Collector.Characteristics 不是 CONCURRENT ?如何检查和设置这个特性?

最佳答案

您的 Collector 不知道您使用了 Supplier 提供的并发集合,只需添加特征并查看它是否按您想要的方式执行;例如:

String s = Stream.of(1, 2, 3, 4).parallel()
.unordered()
.collect(
Collector.of(
() -> new ConcurrentLinkedQueue<>(),
(c, e) -> c.add(e.toString()),
(c1, c2) -> {
c1.addAll(c2);
return c1;
},
Characteristics.CONCURRENT))

关于java - 为什么我的收集器方法没有并行处理数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52054008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com