Why my collector method is not processing data parallely?

amarnath harish :

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 ?

Eugene :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=95305&siteId=1