Reactive Streams in Java: Publisher, Subscriber and the Flow API
Reactive streams model many asynchronous values with demand-driven flow. The Reactive Streams protocol and java.util.concurrent.Flow, SubmissionPublisher and a custom Processor, then a tour of Project Reactor: lazy pipelines, async steps, errors, cold and hot streams, schedulers.
kvi5hnuCode Sprout team member8 min readOn this page
Reactive programming describes a computation as a pipeline over a stream of events: prices, messages, rows, clicks. Instead of writing the steps that fetch and process each value, you declare how values flow and change, and the library pushes each value through the pipeline as it arrives. Article 44 showed that CompletableFuture handles one asynchronous value well. Reactive streams handle zero, one or many values over time, and add something futures lack: a way for a slow consumer to tell a fast producer how much it can take.
The Reactive Streams protocol
In 2015, engineers from Netflix, Pivotal, Typesafe (now Lightbend), Red Hat and others published Reactive Streams, a small specification so that reactive libraries could interoperate. Java 9 copied its four interfaces into the JDK as java.util.concurrent.Flow (JEP 266):
| Interface | Role |
|---|---|
Flow.Publisher<T> | produces items. Its single method is subscribe(subscriber). |
Flow.Subscriber<T> | consumes them: onSubscribe, onNext, onError, onComplete |
Flow.Subscription | the link between the two: request(n) and cancel() |
Flow.Processor<T, R> | both a subscriber and a publisher: a stage in the middle of a pipeline |

The rules that matter most:
- Demand drives delivery. A publisher may call
onNextat most as many times as the subscriber hasrequested in total. That's backpressure (article 46). - Signals are serialized. A subscriber's methods are never called concurrently, so subscriber code needs no locks for its own state.
- One terminal signal. A stream ends with exactly one
onCompleteoronError, and nothing is sent after it.onErrorends the stream. There's no "skip this item and continue" at the protocol level. - No nulls. Items, errors and subscriptions are never
null. cancel()tells the publisher to stop sending, at any time.
The specification has around 40 rules and a compatibility test kit, the TCK, and implementing a Publisher correctly by hand is famously hard. In practice you use a library, and the interfaces are the common language between libraries.
Flow in plain Java
The JDK includes one ready-made publisher, SubmissionPublisher, which buffers submitted items for each subscriber and delivers them asynchronously on an executor (by default ForkJoinPool.commonPool()). The program connects it to a subscriber that logs every signal, puts a processor in the middle, and ends a stream with an error.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
import java.util.function.Function;
import java.util.function.Predicate;
public class Solution {
record Fare(String route, int price) {}
/** Requests one item at a time and logs every signal it receives. */
static final class LoggingSubscriber<T> implements Flow.Subscriber<T> {
private final String name;
private final CountDownLatch done = new CountDownLatch(1);
final CountDownLatch firstItem = new CountDownLatch(1);
private Flow.Subscription subscription;
LoggingSubscriber(String name) { this.name = name; }
@Override public void onSubscribe(Flow.Subscription s) {
subscription = s;
System.out.println(name + " onSubscribe, request(1)");
s.request(1); // nothing flows until we ask
}
@Override public void onNext(T item) {
System.out.println(name + " onNext " + item);
firstItem.countDown();
subscription.request(1); // ready for one more
}
@Override public void onError(Throwable e) {
System.out.println(name + " onError " + e.getMessage());
done.countDown();
}
@Override public void onComplete() {
System.out.println(name + " onComplete");
done.countDown();
}
void await() throws InterruptedException { done.await(); }
}
/** A Processor is both: it subscribes upstream and publishes filtered, transformed items downstream. */
static final class FilterMapProcessor<T, R> extends SubmissionPublisher<R> implements Flow.Processor<T, R> {
private final Predicate<T> keep;
private final Function<T, R> transform;
private Flow.Subscription upstream;
FilterMapProcessor(Predicate<T> keep, Function<T, R> transform) {
this.keep = keep;
this.transform = transform;
}
@Override public void onSubscribe(Flow.Subscription s) { upstream = s; s.request(1); }
@Override public void onNext(T item) {
if (keep.test(item)) submit(transform.apply(item));
upstream.request(1);
}
@Override public void onError(Throwable e) { closeExceptionally(e); }
@Override public void onComplete() { close(); }
}
public static void main(String[] args) throws InterruptedException {
// 1. Publisher -> Subscriber
System.out.println("1. a publisher and a subscriber:");
var fares = new SubmissionPublisher<Fare>(); // delivers on ForkJoinPool.commonPool()
var a = new LoggingSubscriber<Fare>(" A");
fares.subscribe(a);
fares.submit(new Fare("LIS-OSL", 212));
fares.submit(new Fare("LIS-TOS", 389));
fares.close(); // completes the stream after the queued items
a.await();
// 2. Publisher -> Processor -> Subscriber
System.out.println("2. with a processor that keeps fares under 300 and formats them:");
var source = new SubmissionPublisher<Fare>();
var cheap = new FilterMapProcessor<Fare, String>(f -> f.price() < 300, f -> f.route() + " for " + f.price());
var subscriber = new LoggingSubscriber<String>(" B");
source.subscribe(cheap);
cheap.subscribe(subscriber);
for (int price : new int[] {212, 389, 95, 1140}) source.submit(new Fare("LIS-" + price, price));
source.close();
subscriber.await();
// 3. Errors end the stream
System.out.println("3. an error:");
var failing = new SubmissionPublisher<Fare>();
var c = new LoggingSubscriber<Fare>(" C");
failing.subscribe(c);
failing.submit(new Fare("LIS-OSL", 212));
c.firstItem.await(); // closeExceptionally doesn't wait for queued items
failing.closeExceptionally(new IllegalStateException("fare feed disconnected"));
c.await();
}
}
Output:
1. a publisher and a subscriber:
A onSubscribe, request(1)
A onNext Fare[route=LIS-OSL, price=212]
A onNext Fare[route=LIS-TOS, price=389]
A onComplete
2. with a processor that keeps fares under 300 and formats them:
B onSubscribe, request(1)
B onNext LIS-212 for 212
B onNext LIS-95 for 95
B onComplete
3. an error:
C onSubscribe, request(1)
C onNext Fare[route=LIS-OSL, price=212]
C onError fare feed disconnected
- Demand first. The subscriber received nothing until it called
request(1)inonSubscribe, and it asked for each further item fromonNext.close()completed the stream after the queued items had been delivered. - A processor.
FilterMapProcessorsubscribes to the source and publishes to the subscriber, keeping only fares under 300 and formatting them. ExtendingSubmissionPublishergave it a correct publisher half for free. - Errors are terminal.
closeExceptionallyended the stream withonError. Unlikeclose(), it doesn't wait for queued items: in testing, the item submitted just before it was often never delivered, which is why the demo waits for that item first. Useclose()for a normal end.
Plain Flow code is verbose: there are no operators such as filter or map, so every transformation needs a processor. That's the gap reactive libraries fill.
Reactive libraries
| Library | Main types | Notes |
|---|---|---|
| Project Reactor | Flux<T> (0..N items), Mono<T> (0..1) | used by Spring WebFlux, Spring Data reactive repositories, R2DBC drivers |
| RxJava 3 | Flowable (backpressured), Observable, Single, Maybe, Completable | common on Android |
| SmallRye Mutiny | Multi<T>, Uni<T> | used by Quarkus |
| Akka Streams / Pekko Streams | Source, Flow, Sink | stream graphs for the actor ecosystem |
Each interoperates through Reactive Streams publishers: Reactor's Flux and Mono, RxJava's Flowable, Mutiny's Multi (through the JDK's Flow), and Akka or Pekko streams via Sink.asPublisher. Adapters convert between those and java.util.concurrent.Flow (FlowAdapters in the reactive-streams jar, JdkFlowAdapter in Reactor).
A tour of Reactor
This program needs reactor-core on the class path. It was compiled and run with Reactor 3.7.6 on Java 25.
import java.time.Duration;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.core.scheduler.Schedulers;
// Needs reactor-core (io.projectreactor:reactor-core:3.7.x) on the class path
public class ReactorTour {
static Mono<Integer> fareFor(String route) { // an asynchronous lookup
return Mono.fromCallable(() -> 100 + route.chars().sum() % 400)
.delayElement(Duration.ofMillis(50));
}
public static void main(String[] args) {
// 1. A pipeline: nothing happens until subscribe()
Flux<String> cheap = Flux.just(212, 389, 95, 1140)
.doOnNext(f -> System.out.println(" emitted " + f))
.filter(f -> f < 300)
.map(f -> "fare " + f);
System.out.println("1. pipeline built, nothing emitted yet");
cheap.subscribe(
s -> System.out.println(" received " + s),
e -> System.out.println(" error " + e),
() -> System.out.println(" complete"));
// 2. Asynchronous steps: concatMap runs the lookups one after another, in order
// (flatMap would run them concurrently and emit results as they complete)
List<String> routes = List.of("LIS-OSL", "LIS-TOS", "OSL-TOS");
System.out.println("2. fares in route order: " +
Flux.fromIterable(routes).concatMap(ReactorTour::fareFor).collectList().block());
// 3. Errors: a failing step ends the stream unless an operator recovers
System.out.println("3. " + Flux.just("LIS-OSL", "", "OSL-TOS")
.map(r -> { if (r.isEmpty()) throw new IllegalArgumentException("empty route"); return r; })
.onErrorResume(e -> Flux.just("fallback after: " + e.getMessage()))
.collectList().block());
// 4. Cold: every subscriber gets its own run of the source
Flux<Integer> cold = Flux.range(1, 3);
System.out.println("4. cold, two subscribers: " + cold.collectList().block() + " " + cold.collectList().block());
// 5. Hot: a sink pushes to whoever is subscribed right now
Sinks.Many<String> ticks = Sinks.many().multicast().directBestEffort();
StringBuilder early = new StringBuilder(), late = new StringBuilder();
ticks.asFlux().subscribe(t -> early.append(t).append(' '));
ticks.tryEmitNext("t1");
ticks.asFlux().subscribe(t -> late.append(t).append(' '));
ticks.tryEmitNext("t2");
ticks.tryEmitComplete();
System.out.println("5. hot: early subscriber saw [" + early.toString().trim() + "], late one saw [" + late.toString().trim() + "]");
// 6. Where code runs: publishOn switches the thread for the operators after it
System.out.println("6. map ran on: " + Mono.just("x")
.publishOn(Schedulers.boundedElastic())
.map(x -> Thread.currentThread().getName().replaceAll("-\\d+$", "-N"))
.block());
}
}
Output:
1. pipeline built, nothing emitted yet
emitted 212
received fare 212
emitted 389
emitted 95
received fare 95
emitted 1140
complete
2. fares in route order: [215, 223, 229]
3. [LIS-OSL, fallback after: empty route]
4. cold, two subscribers: [1, 2, 3] [1, 2, 3]
5. hot: early subscriber saw [t1 t2], late one saw [t2]
6. map ran on: boundedElastic-N
- Lazy pipelines. Building the
Fluxdid nothing.subscribestarted the flow, and each item went throughfilterandmapone at a time: 212 was emitted and received before 389 was even emitted. The three lambdas passed tosubscribehandleonNext,onErrorandonComplete. - Asynchronous steps.
concatMapturns each route into an asynchronousMonoand keeps the results in route order.flatMapwould run the lookups concurrently and emit fares as they arrive.block()waits for the result, which is fine in amainmethod or a test, but never on an event loop. - Errors. The empty route threw inside
map, which ended the stream withonError.onErrorResumereplaced the rest of the stream with a fallback. The third route was never processed, because an error is terminal. - Cold streams start over for each subscriber: both subscribers got
[1, 2, 3]. Most publishers are cold: a database query, an HTTP call. - Hot streams broadcast to whoever is subscribed at that moment, like a price feed. The late subscriber missed
t1. - Schedulers. Reactor runs operators on the thread that delivers the signal, unless told otherwise.
publishOn(scheduler)moves everything after it to another scheduler:parallel()for CPU work,boundedElastic()for blocking calls.subscribeOnchooses where the source itself runs.
Reactive streams aren't java.util.stream
Both have map and filter, but they're different tools:
java.util.stream.Stream | Reactive streams (Flux, Flow) |
|---|---|
| pulls from a source that's already available | values are pushed as they arrive, asynchronously |
| one terminal operation, then done | subscribers can come and go, and streams can be infinite |
| synchronous (or parallel on the common pool) | asynchronous, with explicit schedulers |
| no flow control | demand signalling with request(n) |
| exceptions are thrown | errors are signals (onError) |
What's current
java.util.concurrent.FlowandSubmissionPublisherhave been unchanged since Java 9, through Java 27. They define the interfaces, but the JDK still has no operator library, andjava.net.http.HttpClientis the main JDK API that usesFlow(for request and response bodies).- Reactor 3.8 (November 2025, used by Spring Boot 4) and RxJava 3 are current; the examples here were run on Reactor 3.7.6. Reactor 3.6 and later can use virtual threads for
boundedElastic()when configured with thereactor.schedulers.defaultBoundedElasticOnVirtualThreadssystem property. - Reactive types remain common in Spring WebFlux, R2DBC and messaging, even as virtual threads take over plain request/response code (article 47).
Common questions
Should I implement Flow.Publisher myself?
Almost never. Use SubmissionPublisher or a library. A hand-written publisher has to handle concurrent request and cancel calls, demand accounting, and the terminal-signal rules, all of which the TCK tests.
What does request(Long.MAX_VALUE) mean?
"Unbounded": send everything as fast as you can. Reactor's subscribe(consumer) does this by default. It switches off backpressure for that subscriber.
Is a Mono just a CompletableFuture?
They overlap, but a Mono is lazy (nothing happens until subscription), can be retried by subscribing again, supports cancellation that propagates upstream, and composes with Flux operators. A CompletableFuture starts work eagerly and represents one specific execution.
Why does nothing happen when I call a reactive repository method?
Because nothing subscribed. Reactive pipelines are lazy: in a WebFlux controller, the framework subscribes to the Mono or Flux you return. Elsewhere, you must subscribe yourself.
Summary
- Reactive streams model asynchronous sequences of zero or more values, with completion or error as the final signal.
- The Reactive Streams protocol, mirrored by
java.util.concurrent.Flow, has four interfaces. Publishers send at most as many items as subscribers request, signals are serialized, and each stream ends with one terminal signal. SubmissionPublisheris the JDK's buffered, asynchronous publisher.close()completes after queued items, whilecloseExceptionally()may drop them.- Libraries such as Reactor add operators, error handling and schedulers. Pipelines are lazy, cold sources restart per subscriber, and hot sources broadcast.
- Reactive streams push asynchronous values with demand signalling, which makes them a different tool from
java.util.stream.
Practice questions
A subscriber calls request(3) in onSubscribe and never calls request again. The publisher has 10 items. How many does the subscriber receive, and what happens to the rest?
Answer
Exactly 3. The publisher may not send more than the total requested. The other 7 stay with the publisher, buffered or not yet produced, until more demand arrives or the subscriber cancels. With a SubmissionPublisher, the 7 wait in the subscriber's buffer, and submit would only block once that buffer (256 items by default) is full (article 46).
In Reactor, Flux.just("a", "", "c").map(this::parse).subscribe(...) fails on the empty string. Does "c" get processed? How could you keep processing after a bad item?
Answer
No. The exception becomes an onError signal, which terminates the stream, so "c" is never processed. To skip bad items, handle the failure per item, for example flatMap(s -> Mono.fromCallable(() -> parse(s)).onErrorResume(e -> Mono.empty())), or use Reactor's onErrorContinue with care.
What's the difference between a cold and a hot publisher? Give an example of each.
Answer
A cold publisher starts producing from the beginning for each subscriber: a database query or Flux.range produces its full sequence for every subscription. A hot publisher produces independently of subscribers, and each subscriber sees only items emitted after it subscribed: a live price feed, UI events, or a Reactor Sinks.many().multicast().
Previous: Event-Driven Java: Event Loops, Callbacks and CompletableFuture
Next: Backpressure in Java: Flow Control With Reactive Streams and Virtual Threads

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.