Parallel Collectors 是一个工具包,可通过 Stream API 简化 Java 中的并行集合处理。
Parallel Collectors 是一个工具包,可通过 Stream API 简化 Java 中的并行集合处理。
Overcoming limitations of standard Parallel Streams Parallel Collectors is a toolkit that eases parallel collection processing in Java using the Stream API without the limitations imposed by standard Parallel Streams.
list.stream()
.collect(parallel(i -> blockingOp(i), toList()))
.orTimeout(1000, MILLISECONDS)
.thenAcceptAsync(System.out::println, executor)
.thenRun(() -> System.out.println("Finished!"));
They are:
CompletableFutures, allowing for timeout specification, composition with other CompletableFutures, and asynchronous processing)Executors and parallelism levels)Collector interface, no magic inside, zero-dependencies, no Stream API internals hacking)Collectors) com.pivovarit
parallel-collectors
4.0.0
com.pivovarit
parallel-collectors
2.6.1
implementation 'com.pivovarit:parallel-collectors:4.0.0'
implementation 'com.pivovarit:parallel-collectors:2.6.1'
Parallel Collectors are intentionally unopinionated, leaving responsibility to users for:
Executors and their lifecycle managementReview the API documentation before deploying in production.
The goal is to use the Stream API without inheriting the limitations of parallel streams, especially for I/O-heavy or structured workloads.
Java's built-in parallelization story is geared toward CPU-bound workloads - parallelStream() runs everything on the shared ForkJoinPool, which makes it a poor fit for blocking I/O, remote calls, database access, or anything that can stall a worker thread. Once that pool is saturated, everything else using it slows down as well.
This library fills that gap. It keeps the Stream API model but replaces the execution strategy:
CompletableFuture integration so you can work asynchronously and apply timeouts, callbacks, or composition naturallyThe main entry point is the com.pivovarit.collectors.ParallelCollectors class - which follows the convention established by java.util.stream.Collectors and features static factory methods returning custom java.util.stream.Collector implementations spiced up with parallel processing capabilities.
By default, collectors use Virtual Threads, but you can optionally provide a custom Executor instance for more control. When using a custom Executor, you are responsible for its lifecycle management.
All parallel collectors are one-off and must not be reused.
Important: parallel(mapper) returns CompletableFuture>, not CompletableFuture>. If you want a List, pass a downstream collector explicitly: parallel(mapper, toList()). The same applies to parallelBy.
flowchart TD
A[Are you ok blocking the caller thread while waiting for processing to finish?] -->|No| B[Use ParallelCollectors.parallel]
A -->|Yes| C{Does the order of elements matter?}
C -->|Yes| D["Use ParallelCollectors.parallelToStream with c -> c.ordered()"]
C -->|No| E[Use ParallelCollectors.parallelToStream]
ParallelCollectors.parallel family returns CompletableFuture while ParallelCollectors.parallelToStream family returns Stream.
Additionally, you can customize:
Executor (defaults to Virtual Threads)batching() configurer optionparallelBy(...) / parallelToStreamBy(...) methodsordered() configurer option (streaming collectors only)Collector (ParallelCollectors.parallel only)executorDecorator() to wrap the resolved executortaskDecorator() to wrap each individual taskAll configuration is done via the CollectingConfigurer (for parallel/parallelBy) or StreamingConfigurer (for parallelToStream/parallelToStreamBy) passed as a Consumer:
list.stream()
.collect(parallel(i -> foo(i), c -> c
.executor(executor)
.parallelism(4)
.batching(),
toList()));
When you use non-batching parallel collectors, every input element is turned into an individual task submitted to an ExecutorService. If you have 1000 elements, you end up submitting 1000 tasks.
Even if you only have two threads processing them, both threads hammer the same task queue, repeatedly competing for the next piece of work. That competition creates contention, and overall overhead.
This behaviour resembles a primitive form of work-stealing, where each worker repeatedly tries to grab the next available task. Work-stealing is great in scenarios where task durations vary significantly, since it keeps faster workers busy, but it's not free.
However, if the processing time for all subtasks is similar, it might be better to distribute tasks in batches to avoid excessive contention.
Without batching:
Thread 1: [] [] [] [] [] [] [] [] [] [] [] ... (500 tiny tasks)
Thread 2: [] [] [] [] [] [] [] [] [] [] [] ... (500 tiny tasks)
With batching:
Thread 1: [--------------------------------------------------] (1 large task)
Thread 2: [--------------------------------------------------] (1 large task)
The difference in performance for lightweight tasks can be enormous:
Benchmark Mode Cnt Score Error Units
BatchedVsNonBatchedBenchmark.batch thrpt 5 41558.548 ± 959.057 ops/s
BatchedVsNonBatchedBenchmark.normal thrpt 5 254.869 ± 5.667 ops/s
Batching can be enabled via the batching() configurer option:
list.stream()
.collect(parallel(i -> foo(i), c -> c.parallelism(4).batching(), toList()));
The parallelBy(...) and parallelToStreamBy(...) methods allow you to classify input elements by a key and process each group in parallel. Each group is guaranteed to be processed on a single thread, and results are returned as Group entries:
CompletableFuture>> result = tasks.stream()
.collect(parallelBy(Task::groupId, t -> compute(t)));
CompletableFuture>> result = tasks.stream()
.collect(parallelBy(Task::groupId, t -> compute(t), toList()));
The Group record provides key() and values() accessors, plus a map() method for transforming values while preserving the grouping key.
Two decorator options let you add cross-cutting behavior without replacing the executor:
executorDecorator(UnaryOperator) wraps the resolved executor (the virtual-thread default or a custom one) and returns a replacement. It is invoked once per collector, before any tasks are submitted. This is a natural fit for intercepting every execute() call, for example to plug in a monitoring layer.
The returned executor must not drop or discard tasks — doing so will cause the collector to wait indefinitely for results that will never arrive.
list.stream()
.collect(parallel(i -> foo(i), c -> c
.executorDecorator(exec -> task -> {
metrics.incrementAndGet();
exec.execute(task);
}),
toList()));
taskDecorator(UnaryOperator) wraps each individual task before it is handed to the executor. Unlike the executor decorator, it runs on the worker thread and is re-applied for every element. This makes it the right tool for propagating thread-local context (MDC, OpenTelemetry spans, SecurityContext) into worker threads:
var snapshot = MDC.getCopyOfContextMap();
list.stream()
.collect(parallel(i -> foo(i), c -> c
.taskDecorator(task -> () -> {
MDC.setContextMap(snapshot);
try {
task.run();
} finally {
MDC.clear();
}
}),
toList()));
Both decorators can be combined and each may be specified at most once per configurer.
Parallel Collectors expose results wrapped in CompletableFuture instances, which provides great flexibility and the possibility of working with them in a non-blocking fashion:
CompletableFuture> result = list.stream()
.collect(parallel(i -> foo(i), toList()));
This makes it possible to conveniently apply callbacks and compose with other CompletableFutures:
list.stream()
.collect(parallel(i -> foo(i), toSet()))
.thenAcceptAsync(System.out::println, otherExecutor)
.thenRun(() -> System.out.println("Finished!"));
Or just join() if you just want to block the calling thread and wait for the result:
List result = list.stream()
.collect(parallel(i -> foo(i), toList()))
.join();
What's more, since JDK9, you can even provide your own timeout easily.
i -> foo(i) in parallel using Virtual Threads and collect to ListCompletableFuture> result = list.stream()
.collect(parallel(i -> foo(i), toList()));
i -> foo(i) in parallel on a custom Executor with max parallelism of 4 and collect to SetExecutor executor = ...
CompletableFuture> result = list.stream()
.collect(parallel(i -> foo(i), c -> c
.executor(executor)
.parallelism(4),
toSet()));
i -> foo(i) in parallel with batching and collect to LinkedListCompletableFuture> result = list.stream()
.collect(parallel(i -> foo(i), c -> c.parallelism(4).batching(),
toCollection(LinkedList::new)));
i -> foo(i) in parallel and stream results in completion orderlist.stream()
.collect(parallelToStream(i -> foo(i)))
.forEach(i -> ...);
i -> foo(i) in parallel and stream results in the original orderlist.stream()
.collect(parallelToStream(i -> foo(i), c -> c.ordered()))
.forEach(i -> ...);
CompletableFuture>> result = tasks.stream()
.collect(parallelBy(Task::groupId, t -> compute(t)));
i -> foo(i) in parallel with full configurationExecutor executor = ...
CompletableFuture> result = list.stream()
.collect(parallel(i -> foo(i), c -> c
.executor(executor)
.parallelism(64)
.batching(),
toList()));
taskDecoratorvar snapshot = MDC.getCopyOfContextMap();
CompletableFuture> result = list.stream()
.
暂无开放 Issues,或尚未同步最近议题。