Gatherers mapConcurrent Parallel Mapping

Run stream mapping on up to N virtual threads with Gatherers.mapConcurrent, which fans work out concurrently yet keeps encounter order in the output.

JavaData Fetching

Code

snippet
import java.util.List;
import java.util.stream.Gatherers;

public class ConcurrentMapGatherer {

    record Probe(String id, int ms) {}

    public static void main(String[] args) {
        List<Probe> probes = List.of(
                new Probe("a", 30), new Probe("b", 10),
                new Probe("c", 20), new Probe("d", 5));

        // mapConcurrent:最多 3 个虚拟线程并发跑,输出仍保持 encounter order
        List<String> results = probes.stream()
                .gather(Gatherers.mapConcurrent(3, p -> {
                    try {
                        Thread.sleep(p.ms());
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    return p.id() + "@" + p.ms();
                }))
                .toList();

        System.out.println(results);
        System.out.println("ordered: " + results.equals(List.of("a@30", "b@10", "c@20", "d@5")));
    }
}

How the snippet works

The snippet is organized around the classes ConcurrentMapGatherer and Probe and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Applying it

Entry signature: public static void main(String[] args)

Mechanics of the snippet

Thread.currentThread().interrupt();
return p.id() + "@" + p.ms();
Thread.sleep(p.ms());

FAQ

What does Gatherers mapConcurrent Parallel Mapping print when run?
Execute the whole file; each printed line is prefixed with a label like `ordered:`.