Object
ParallelConsumer<T>
- All Implemented Interfaces:
AutoCloseable
,Consumer<T>
Parallel streams may partition the stream in any order which means that there is no guarantee
that items which are in the top of the stream will be processed first. Here is an example:
AtomicInteger c = new AtomicInteger();
Consumer<Integer> consumer = s -> {
if (c.incrementAndGet() < 15)
System.out.println(s);
};
System.out.println("Parallel stream:");
range(0, 1000)
.parallel()
.boxed()
.forEach(consumer);
System.out.println("Total: " + c);
May produce:
Parallel stream: 656 657 658 659 660 661 662 663 664 665 666 667 668 77 Total: 1000
The output of course differs every time you run the code.
Parallel consumer on the other hand allows you to process items of the stream in parallel but guaranteeing that items will be taken in order.
System.out.println("Parallel consumer:");
c.set(0);
try (ParallelConsumer<Integer> pconsumer = new ParallelConsumer<>(consumer)) {
range(0, 1000)
.boxed()
.forEach(pconsumer);
}
System.out.println("Total: " + c);
May produce:
Parallel consumer: 0 1 4 5 2 3 6 7 8 9 10 12 13 11 Total: 1000
It is achieved by making consumers to take items from the internal queue.
If your application finishes but does not terminate it may be because:
- you are leaking parallel consumers (make sure to close them)
- one of your consumers still running preventing JVM from stopping
All exceptions in worker threads by default will be printed to stderr unless the exception handler is defined.
-
Constructor Summary
ConstructorDescriptionParallelConsumer
(Consumer<T> consumer) ParallelConsumer
(Consumer<T> consumer, int parallelismLevel) ParallelConsumer
(Consumer<T> consumer, Thread.UncaughtExceptionHandler exHandler) -
Method Summary