Parallel Operations: Several Elements at Once

Run the tasks for several elements at the same time, batch elements for a bulk call, and merge streams.

What You'll Learn

  • Run several elements' tasks at once, up to a limit you set, keeping their order or taking each result as it arrives
  • Say how far each operation reads ahead of the consumer, and which thread reads the source
  • Choose a concurrency, and keep going when one element's task fails
  • Batch elements for a call that takes several at a time
  • Merge streams read at the same time

See Example Code

The code on this page is VStreamParBook.java: the page includes it, so the build compiles and runs it. VStreamParBookTest.java holds what the page says each operation does.


Several quotes at once

mapTask runs one element's task at a time, so four courier quotes that each take a second take four seconds. VStreamPar runs several at once, each on a virtual thread.

A preview API

VStreamPar is built on StructuredTaskScope, a preview feature in Java 25, so code that names it needs --enable-preview to compile and to run. VStreamPath's parEvalMap and parEvalMapUnordered compile without it and need it when they run, as the VTask page explains for VTaskPath. The HKJ Gradle plugin adds it by default.

The code on this page uses the order feed and the Courier from the VStream page, with these imports:

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.higherkindedj.hkt.effect.Path;
import org.higherkindedj.hkt.trymonad.Try;
import org.higherkindedj.hkt.vstream.VStream;
import org.higherkindedj.hkt.vstream.VStreamPar;
import org.higherkindedj.hkt.vtask.VTask;

The paid orders are the stream to quote for, and ZONED_COURIER quotes by where each customer lives, so each quote shows which order it belongs to:

  static VStream<Order> paidOrders() {
    return orders(new PagedFeed(ORDERS)).filter(VStreamBook::paid);
  }

  // A courier whose quote depends on where the customer lives
  static final Map<String, BigDecimal> RATES =
      Map.of(
          "Ada", new BigDecimal("4.99"),
          "Alan", new BigDecimal("6.49"),
          "Edsger", new BigDecimal("3.99"),
          "Ken", new BigDecimal("5.49"));

  static final Courier ZONED_COURIER = order -> RATES.get(customer(order));

parEvalMap(stream, concurrency, f) asks for up to concurrency quotes at once, and gives them in the orders' order:

    // At most four quotes asked for at once, and given in the orders' order
    VStream<BigDecimal> quotes =
        VStreamPar.parEvalMap(paidOrders(), 4, order -> VTask.of(() -> ZONED_COURIER.quote(order)));

    List<BigDecimal> inOrder = quotes.toList().run();
    // [4.99, 6.49, 3.99, 5.49]

It works a batch at a time. A pull reads up to concurrency elements from the source, forks a task for each, and waits for every task in the batch. It answers that pull with the first result, and answers the pulls after it from the rest of the batch:

%%{init: {"sequence": {"actorMargin": 20, "diagramMarginX": 10}}}%%
sequenceDiagram
    accTitle: How parEvalMap answers the pulls for four quotes
    accDescr: The first pull reads four paid orders from the source, forks a quote task for each, and waits for all four before it answers with the first quote. The next three pulls are answered from the batch. The fifth pull starts the next batch: it reads the source again, finds its end, and answers Done.
    participant L as toList
    participant P as parEvalMap(4)
    participant S as paid orders
    participant Q as quote tasks
    L->>P: pull 1
    P->>S: read four orders
    P->>Q: fork four quotes
    Q-->>P: all four quotes
    P-->>L: Emit 4.99
    L->>P: pulls 2 to 4
    P-->>L: Emit 6.49, 3.99, 5.49
    L->>P: pull 5
    P->>S: read
    S-->>P: Done
    P-->>L: Done

The arrows to the right are pulls and forks, and the dashed arrows back are what each gives. A batch's results wait for its slowest task. The source is read again only after every result of the batch has been taken. The tail of the batch's last result is the next batch, so pull 5 reads the source and finds its end.

The source is read on the thread that pulls, and each task runs on a virtual thread of its own, which sees the caller's ScopedValue bindings. A concurrency of 1 runs the tasks one at a time, as mapTask does, but each on a virtual thread.

In order, or as each arrives

When the order of the results does not matter, parEvalMapUnordered gives each one as its task completes, so a slow quote holds back only itself:

    // Each quote given as soon as the courier answers it
    VStream<String> arriving =
        VStreamPar.parEvalMapUnordered(
            paidOrders(),
            4,
            order -> VTask.of(() -> customer(order) + " " + ZONED_COURIER.quote(order)));

    List<String> asTheyArrived = arriving.toList().run();
    List<String> sorted = asTheyArrived.stream().sorted().toList();
    // [Ada 4.99, Alan 6.49, Edsger 3.99, Ken 5.49]

The quotes arrive in whatever order the courier answers, so the example sorts them to show they are all there.

parEvalMapparEvalMapUnordered
Order of the resultsThe elements' orderThe order the tasks complete
A slow task holds backIts whole batch, and the nextOnly its own result
Reads ahead of the consumerA batch of up to concurrency elementsUp to concurrency elements whose results are not yet pulled
Reads the source onThe thread that pullsA virtual thread of its own
Tasks see the caller's ScopedValue bindingsYesNo

parEvalMapUnordered starts the next element's task each time you take a result. If you stop reading part-way, close the tail you hold, or the run's thread is left waiting. take and the other operations that stop early close it for you.

parEvalFlatMap(stream, concurrency, f) builds the stream f gives for each element, up to concurrency at once through parEvalMap, then reads those streams one after another, in order. Closing it closes each stream it built but never reached, so their finalisers run when a take stops early or a failure ends the stream first.

Choosing a concurrency

For tasks that wait on I/O, such as calls to another service, set concurrency to the number of calls that service accepts at once. Virtual threads make the waiting cheap, so the service's limit is the one that counts. For tasks that compute, more than Runtime.getRuntime().availableProcessors() gains nothing, since that is how many virtual threads run at once by default. Each stage of a pipeline takes its own concurrency, so a stage that downloads can run eight at once and the stage that uploads after it two.

When a task fails

A task that fails makes its element a failure in its place, as a failed mapTask task does, and the other tasks run on. PATCHY_COURIER, from When an element fails, quotes 4.99 for every order but cannot quote for Edsger, and FLAT_RATE is 9.99:

    VStream<BigDecimal> patchy =
        VStreamPar.parEvalMap(
            paidOrders(), 4, order -> VTask.of(() -> PATCHY_COURIER.quote(order)));

    Try<List<BigDecimal>> held = patchy.toList().runSafe();
    // Failure(java.io.IOException: no courier serves Edsger's address)
    List<BigDecimal> recovered = patchy.recover(error -> FLAT_RATE).toList().run();
    // [4.99, 4.99, 9.99, 4.99]

Without a recover, the stream fails with the courier's own exception when it reaches Edsger's quote. A recover after the parallel operation gives a value in its place, and the stream goes on with the next quote. parEvalMapUnordered hands on a task's failure as the task completes, as it does a result. In parEvalFlatMap, a call of f that fails is a failed task, so recover gives one value in place of the stream that call would have built.

Two failures still end the stream. A function that throws, rather than returning a task that fails, ends it as it would mapTask, so do the work inside the task, as VTask.of does. A task that fails with an InterruptedException ends it at once: the tasks still running are cancelled, and parEvalMap hands on none of that batch's results. A recover after it lets the interrupt through, as Running a stream says, so the run fails with it.

A failed element from further up is handed on in the same way. When a mapTask task fails before the parallel operation, its element passes through as a failure, so a recover after the parallel operation gives a value in its place and the stream goes on. parEvalMap, parEvalMapUnordered and parEvalFlatMap all do this, while a merge of several streams ends there. Any other failure further up, such as a map that throws, ends the stream, after the elements read before it.

Chunking operations

chunk(size) groups elements into batches of up to size, and chunkWhile starts a new batch wherever a test fails between neighbours:

    List<List<String>> pairs =
        paidOrders()
            .chunk(2)
            .map(batch -> batch.map(VStreamBook::customer).toJavaList())
            .toList()
            .run();
    // [[Ada, Alan], [Edsger, Ken]]
    List<List<String>> byStatus =
        orders(new PagedFeed(ORDERS))
            .chunkWhile((earlier, later) -> earlier.status() == later.status())
            .map(batch -> batch.map(VStreamBook::customer).toJavaList())
            .toList()
            .run();
    // [[Ada], [Grace], [Alan, Edsger], [Barbara], [Ken]]

Each batch is a NonEmptyList, since a chunk is given only once it holds an element, so head() and reduce on it always have a value. The last chunk may be shorter, and an empty stream gives no chunks. A size larger than the stream, even Integer.MAX_VALUE, gives one chunk of every element, without reserving room for the rest. A parEvalMap concurrency that large reads the whole stream as one batch in the same way.

A batch suits a call that takes several elements at once, such as a warehouse that packs a list of orders:

  // A warehouse packs several orders in one call, which blocks until it answers
  interface Warehouse {
    List<String> pack(List<Order> orders) throws IOException;
  }

chunk followed by parEvalMap makes one call for each batch, with up to concurrency calls at once. The warehouse's pack blocks and can throw, so each call runs as a task. mapChunked(size, f) suits a function that cannot fail and does not block: it applies f to each batch and flattens the lists it gives:

    // Two orders to a call, and two calls at once
    VStream<List<String>> boxes =
        VStreamPar.parEvalMap(
            paidOrders().chunk(2), 2, batch -> VTask.of(() -> WAREHOUSE.pack(batch.toJavaList())));

    List<List<String>> packed = boxes.toList().run();
    // [[box for Ada, box for Alan], [box for Edsger, box for Ken]]
    List<String> labels =
        paidOrders()
            .mapChunked(2, batch -> batch.map(order -> "label for " + customer(order)).toJavaList())
            .toList()
            .run();
    // [label for Ada, label for Alan, label for Edsger, label for Ken]

Merging streams

VStreamPar.merge reads several streams at the same time, each on a virtual thread of its own, and gives each element as it arrives from any of them. The sources' threads do not see the caller's ScopedValue bindings:

    VStream<String> london = orders(new PagedFeed(ORDERS.subList(0, 3))).map(VStreamBook::customer);
    VStream<String> edinburgh =
        orders(new PagedFeed(ORDERS.subList(3, 6))).map(VStreamBook::customer);

    List<String> everyCustomer = VStreamPar.merge(london, edinburgh).toList().run();
    List<String> alphabetical = everyCustomer.stream().sorted().toList();
    // [Ada, Alan, Barbara, Edsger, Grace, Ken]

The order depends on which feed answers first, so the example sorts the names. When the consumer stops early, with take(n) or headOption() for example, the merge is closed. It interrupts any source still being read and waits for the sources' threads to stop. Then it closes each source that had not finished, so each source's finalisers run. A source failing stops the merge in the same way. A source finaliser that fails while the merge closes is dropped, since the merge has already stopped.

merge reads ahead without a limit

A merge of several streams reads each source as fast as the source gives elements, and holds the elements you have not pulled yet without a limit. While the consumer is slower than its sources, the backlog can grow to every element they give, so a fast endless source fills memory, and so can a large finite one. Bound an endless source with take or takeWhile before merging it, and merge finite sources only when all they give fits in memory. A merge of one stream is that stream, so it reads no further ahead than that stream does.

How far each operation reads ahead

A VStream is read by pulling, so a consumer that stops pulling stops the reading. Each operation reads only so far ahead of it:

OperationReads ahead of the consumer
parEvalMap, parEvalFlatMapOne batch of up to concurrency elements, at a pull
parEvalMapUnorderedUp to concurrency elements whose results are not yet pulled
chunk(size), mapChunked(size, f)One batch of up to size elements
merge of several streamsEvery element its sources give, without a limit

Those bounds are why a VStream needs no backpressure protocol, the signal by which a consumer tells a producer how much it can take, of the kind Project Reactor's streams use. When the consumer is slow, the operation waits, and a waiting virtual thread holds no platform thread. A merge of several streams is the exception, as its warning says.

On a VStreamPath

VStreamPath has parEvalMap, parEvalMapUnordered, chunk and mapChunked too:

    List<BigDecimal> viaPath =
        Path.vstream(paidOrders())
            .parEvalMap(4, order -> VTask.of(() -> ZONED_COURIER.quote(order)))
            .toList()
            .unsafeRun();
    // [4.99, 6.49, 3.99, 5.49]

Collecting the results

toList() collects what a parallel operation gives, as each example on this page does. The work runs in parallel inside the tasks parEvalMap's function returns; collecting is reading the stream, one pull at a time, so it cannot be parallel itself.

VStreamPar.parCollect(stream, batchSize), VStreamPath.parCollect and PathOps.parCollectVStream are deprecated for removal in 0.7.0. Each gives what toList() gives. The 0.7.0 deprecation recipe rewrites each call to toList(), and marks any call it cannot rewrite safely.

Methods

MethodWhat it does
VStreamPar.parEvalMap(stream, concurrency, f)Runs up to concurrency tasks at once, a batch at a time, and keeps the elements' order
VStreamPar.parEvalMapUnordered(stream, concurrency, f)Runs up to concurrency tasks at once, and gives each result as its task completes
VStreamPar.parEvalFlatMap(stream, concurrency, f)Builds up to concurrency of f's streams at once, and reads them in order
VStreamPar.merge(streams), VStreamPar.merge(first, second)Reads every stream at once, and gives each element as it arrives
stream.chunk(size), stream.chunkWhile(test)Batches of up to size elements, or of neighbours that pass the test
stream.mapChunked(size, f)Applies f to each batch, and flattens the lists it gives

When to use parallel operations

You needUse
A task for each element, several at once, results in orderparEvalMap
The same, each result as soon as it is readyparEvalMapUnordered
One call for several elementschunk, then parEvalMap
Elements from several sources as they arrivemerge, with endless sources bounded
One task at a time, on the caller's threadmapTask, on the VStream page
A few independent tasks, not a streamStructured Concurrency

Hands-On Learning

Practise parallel streams in TutorialVStreamParallel (8 exercises).

Benchmarks: VStreamBenchmark measures parEvalMap, parEvalMapUnordered and the chunking operations. Performance says what it measures and how to run it, and Benchmarks covers every benchmark.


Previous: HKT and Type Classes Next: Performance