Why my collector method is not processing data parallely?

China☆狼群 提交于 2019-12-19 09:29:12

问题


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.

also

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.

from the document

this means the collect method with supplier(Concurrent-thread-safe)should have Collector.Characteristics.CONCURRENT. and thus should not maintain any order.

but my code

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());

always prints the result in the encountered order. does this mean my Collector.Characteristics is not CONCURRENT ? how to check and set this characteristics ?


回答1:


Your Collector does not know that you use a concurrent collection provided by Supplier, just add the characteristic and see that it is executed the way you want to; for example:

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))


来源:https://stackoverflow.com/questions/52054008/why-my-collector-method-is-not-processing-data-parallely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!