Java › Standard

Java concurrency from executors to futures and Flow

Trace Java concurrency from JSR 166 to virtual threads, compose CompletableFuture tasks, and follow Java Flow demand for stream backpressure.

Java concurrency from executors to futures and Flow

I use an executor to decide where a task runs, a future to compose one result, and a stream protocol when results arrive continuously. Java’s concurrency APIs grew in those three directions.

The examples use Java 21, with the original release for each API noted below.

How java.util.concurrent evolved

ReleaseAPIWhat it enables
Java 5, JSR 166ExecutorService, BlockingQueue, ConcurrentHashMap, ReentrantLockTask submission and reusable concurrent building blocks
Java 7, JSR 166yForkJoinPool and RecursiveTaskDivide-and-conquer work and work stealing
Java 8, JSR 166eCompletableFuture and StampedLockAsynchronous composition and additional locking strategies
Java 9, JEP 266java.util.concurrent.FlowReactive Streams-style demand through JDK interfaces
Java 21, JEP 444newVirtualThreadPerTaskExecutor()One lightweight thread per task with the existing executor contract

The executor abstraction lets a caller submit tasks without choosing a specific thread implementation. A virtual-thread executor can therefore service the same blocking methods with one virtual thread per task. It improves scalability for waiting on I/O. CPU-bound work and finite downstream capacity still need their own limits.

flowchart TD
    J5["Java 5: executors"] --> J7["Java 7: fork/join"]
    J7 --> J8["Java 8: futures"]
    J8 --> J9["Java 9: Flow"]
    J9 --> J21["Java 21: virtual threads"]

Composing independent calls with CompletableFuture

An order detail view can fetch its price and inventory independently, then combine the results. The example submits both calls to an explicit executor. thenCombine waits for both successful results, and the inventory stage uses a fallback when that is acceptable to the caller.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// src/main/java/com/example/order/OrderAggregationService.java
package com.example.order;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class OrderAggregationService implements AutoCloseable {

    // Use a dedicated executor for blocking I/O.
    // A virtual-thread executor is another option on Java 21 or later.
    private final ExecutorService ioExecutor = Executors.newVirtualThreadPerTaskExecutor();

    public OrderSummary loadOrderSummary(String userId, String productId) {
        CompletableFuture<ProductInfo> productFuture = CompletableFuture
                .supplyAsync(() -> fetchProduct(productId), ioExecutor)
                .orTimeout(2, TimeUnit.SECONDS);

        CompletableFuture<Integer> stockFuture = CompletableFuture
                .supplyAsync(() -> fetchStock(productId), ioExecutor)
                .orTimeout(2, TimeUnit.SECONDS)
                .exceptionally(ex -> 0); // Fall back when the inventory lookup fails.

        CompletableFuture<String> gradeFuture = CompletableFuture
                .supplyAsync(() -> fetchMemberGrade(userId), ioExecutor)
                .orTimeout(2, TimeUnit.SECONDS)
                .exceptionally(ex -> "STANDARD");

        return productFuture
                .thenCombine(stockFuture, (product, stock) -> new PartialOrder(product, stock))
                .thenCombine(gradeFuture, (partial, grade) ->
                        new OrderSummary(partial.product().name(), partial.stock(), grade))
                .join();
    }

    private ProductInfo fetchProduct(String productId) {
        return new ProductInfo(productId, "Mechanical Keyboard");
    }

    private int fetchStock(String productId) {
        return 42;
    }

    private String fetchMemberGrade(String userId) {
        return "VIP";
    }

    @Override
    public void close() {
        ioExecutor.close();
    }

    public record ProductInfo(String id, String name) {}
    private record PartialOrder(ProductInfo product, int stock) {}
    public record OrderSummary(String productName, int availableStock, String memberGrade) {}
}

thenApply transforms one result, thenCompose chains another asynchronous action, and thenCombine joins two independent stages. A stage without an explicit async executor can run on the thread that completes the preceding stage. The default async methods usually use the common fork-join pool, so I avoid placing unrelated blocking network calls there.

Timeout and fallback policies deserve separate tests. A timeout on a future does not necessarily cancel the underlying network call, so set a time limit on the client as well. The example defaults inventory to zero. If a timeout and a genuinely out-of-stock product have different business meanings, carry that distinction in the result.

Demand in the Flow API

A Flow.Publisher supplies items to a Flow.Subscriber through a Flow.Subscription. The subscriber sends request(n) to advertise demand. The publisher must stay within the outstanding demand when it invokes onNext. The subscriber can request more, cancel, or receive a terminal onComplete or onError signal.

sequenceDiagram
    participant P as Publisher
    participant S as Subscriber
    P->>S: onSubscribe(subscription)
    S->>P: request(2)
    P-->>S: onNext(first)
    P-->>S: onNext(second)
    S->>P: request(2)
    P-->>S: onComplete()

Here the subscriber processes a small batch and then requests another. That allows the consumer to pace the producer. The producer also needs boundaries for work and buffering upstream of the subscription.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// src/main/java/com/example/flow/BackpressureDemo.java
package com.example.flow;

import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;

public class BackpressureDemo {

    public static void main(String[] args) throws InterruptedException {
        try (SubmissionPublisher<String> publisher = new SubmissionPublisher<>()) {
            publisher.subscribe(new BoundedSubscriber(2));

            for (int i = 1; i <= 5; i++) {
                publisher.submit("event-" + i);
            }
        }
        Thread.sleep(200);
    }

    static class BoundedSubscriber implements Flow.Subscriber<String> {
        private final int batchSize;
        private Flow.Subscription subscription;
        private int processedInBatch = 0;

        BoundedSubscriber(int batchSize) {
            this.batchSize = batchSize;
        }

        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            this.subscription = subscription;
            // Request the initial batch.
            this.subscription.request(batchSize);
        }

        @Override
        public void onNext(String item) {
            System.out.println("Received: " + item);
            processedInBatch++;
            if (processedInBatch == batchSize) {
                processedInBatch = 0;
                subscription.request(batchSize); // Request the next batch after processing this one.
            }
        }

        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
        }

        @Override
        public void onComplete() {
            System.out.println("Stream completed.");
        }
    }
}

Reactor and Spring WebFlux use the Reactive Streams interfaces. Reactor’s JdkFlowAdapter bridges those types and Java Flow. The Java HTTP client also uses Flow types for streaming request and response bodies.

Selecting and testing the right abstraction

Start with one result or many. An executor is enough to submit a task, and a future is useful when several finite tasks need composition. Flow is a better fit when the result is a stream and downstream demand should control delivery. In the order example, test a successful combination, one failed dependency, and a slow dependency separately. For a stream, test finite demand, cancellation, and a terminal error as well as completion.

This post is licensed under CC BY 4.0 by the author.