Reactive Streams and backpressure
What you will learn
A reactive publisher sends values to a subscriber according to demand. The subscriber receives a subscription, requests a positive number of items, and can cancel it. Backpressure helps a fast producer avoid overwhelming a slower consumer; it is not a promise of unlimited buffering or a guarantee that all upstream systems can slow down.
- Trace subscription, request, next and terminal signals.
- Demonstrate demand and bounded overflow using JDK Flow.
- Distinguish backpressure from buffering and cancellation.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Reactor and WebFlux examples require the companion Maven project. Their predicted results are not execution evidence.
Request two, then one
import java.util.concurrent.Flow;import java.util.concurrent.SubmissionPublisher;import java.util.ArrayList;import java.util.List;public class Main { static class Probe implements Flow.Subscriber<Integer> { Flow.Subscription subscription; final List<Integer> values = new ArrayList<>(); Throwable error; boolean complete; public void onSubscribe(Flow.Subscription s) { subscription = s; } public void onNext(Integer n) { values.add(n); } public void onError(Throwable t) { error = t; } public void onComplete() { complete = true; } } public static void main(String[] args) { var probe = new Probe(); try (var publisher = new SubmissionPublisher<Integer>(Runnable::run, 4)) { publisher.subscribe(probe); publisher.submit(10); publisher.submit(20); publisher.submit(30); System.out.println(probe.values); probe.subscription.request(2); System.out.println(probe.values); probe.subscription.request(1); System.out.println(probe.values); } System.out.println(probe.complete); }}Expected output:
[][10, 20][10, 20, 30]trueThree items fit in the buffer but none are delivered until demand is signaled. Closing sends completion after pending items are delivered.
Signal contract
Text diagram: subscribe → onSubscribe(subscription) → request(n) → up to n onNext signals → onComplete OR onError. Terminal signals need no outstanding demand; the publisher must serialize signals for each subscriber. Demand is cumulative, saturating at Long.MAX_VALUE. Non-positive requests are errors. Cancellation is eventual and may race with already-in-flight signals; it is not completion. JDK Flow and Reactive Streams have corresponding interfaces but different Java types.
Buffer policy
Demand limits delivery, not necessarily source creation. A source that cannot slow down needs bounded buffering, loss, rejection or another explicitly documented policy. SubmissionPublisher.submit can block when its buffer is full; offer can reject for lagging subscribers. The direct executor below is a controlled teaching fixture, not a production scheduling choice. Never submit indefinitely without demand.
Reject buffer overflow
import java.util.concurrent.Flow;import java.util.concurrent.SubmissionPublisher;import java.util.ArrayList;import java.util.List;public class Main { static class Probe implements Flow.Subscriber<Integer> { Flow.Subscription subscription; final List<Integer> values = new ArrayList<>(); Throwable error; boolean complete; public void onSubscribe(Flow.Subscription s) { subscription = s; } public void onNext(Integer n) { values.add(n); } public void onError(Throwable t) { error = t; } public void onComplete() { complete = true; } } public static void main(String[] args) { var probe = new Probe(); try (var publisher = new SubmissionPublisher<Integer>(Runnable::run, 2)) { publisher.subscribe(probe); publisher.offer(1, (s, v) -> false); publisher.offer(2, (s, v) -> false); int result = publisher.offer(3, (s, v) -> false); System.out.println(result < 0); probe.subscription.request(2); System.out.println(probe.values); } }}Expected output:
true[1, 2]The capacity-two fixture declines the third offer while demand is zero. A negative result reports a drop; the subscriber subsequently receives the first two values.
Verify demand in Reactor
Source-reviewed, NOT RUN. File lab-fixtures/reactive-v45/src/test/java/lab/DemandTest.java; use the companion lab README.
package lab;import java.time.Duration;import org.junit.jupiter.api.Test;import reactor.core.publisher.Flux;import reactor.test.StepVerifier;class DemandTest { @Test void demand() { StepVerifier.create(Flux.range(1, 3), 0) .expectSubscription().thenRequest(2).expectNext(1, 2) .thenRequest(1).expectNext(3).expectComplete() .verify(Duration.ofSeconds(2)); }}Predicted behavior: No values before demand; 1, 2, then 3 and completion.
StepVerifier starts with zero demand and requests explicitly. A finite verify timeout prevents hanging tests.
Common mistakes
Do not assume request(2) means only two items exist upstream. Do not use submit on the same thread that must release demand when the queue is full. A negative request is not cancellation.
Practice
Subscribe to a capacity-four SubmissionPublisher with a direct executor, submit 7 and 8, request one item, print the values, request the next and print again.
Expected output:
[7][7, 8]Compare with the manual review criteria.
Official reading: Flow · Subscription · SubmissionPublisher · StepVerifier. Reactor and WebFlux execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reactive Streams and backpressure — knowledge check
Reactive programming reasoning.
What does request(3) permit?
Must a completion wait for positive demand when no values remain?
What is a non-positive request?
What can offer return when a subscriber drops a value?
What does cancellation guarantee?