Java
Backpressure
Learn flow control with backpressure.
Backpressure
Backpressure is the consumer telling the producer how much data it wants. So that a fast Publisher does not overwhelm a slow Subscriber, the Subscriber asks for only n items with request(n).
This way the Publisher sends no items before the subscriber is ready, preventing memory bloat. Backpressure is the most important feature of Reactive Streams and the main difference from the classic observer pattern. Delivery without demand is forbidden by the contract.
Demand strategies
Two common strategies exist. One at a time: after each onNext, request(1) is called; this suits slow processing. Unbounded: request(Long.MAX_VALUE) asks for all items, disabling backpressure.
Example: a log subscriber that processes each line one by one uses the one-at-a-time strategy. A subscriber that processes in batches can raise performance with larger requests. The right strategy depends on the subscriber's processing speed and the Publisher's production rate.
Exercise Print the item count received by demand
Define a LimitPublisher class that implements Publisher<Integer>. The request(long n) method inside subscribe loops n times calling s.onNext(i), then calls s.onComplete(). In main, an anonymous Subscriber: onSubscribe calls s.request(2), onNext does count++, and onComplete prints the count with System.out.println(count).
Show example solution
import java.util.concurrent.Flow.*;
class LimitPublisher implements Publisher<Integer> {
public void subscribe(Subscriber<? super Integer> s) {
s.onSubscribe(new Subscription() {
public void request(long n) {
for (int i = 0; i < n; i++) s.onNext(i);
s.onComplete();
}
public void cancel() { }
});
}
}
public class BackpressureDemo {
public static void main(String[] args) {
new LimitPublisher().subscribe(new Subscriber<Integer>() {
int count;
public void onSubscribe(Subscription s) { s.request(2); }
public void onNext(Integer v) { count++; }
public void onError(Throwable t) { }
public void onComplete() { System.out.println(count); }
});
}
}
Test yourself
-
Through which method is backpressure controlled?
- onNext
- onComplete
- request
- subscribe
Show answer
request — request(n) states the demanded amount.
-
Match the backpressure concepts
- request
- Demand amount
- Subscriber
- Sets the demand
- Publisher
- Follows the demand
- Long.MAX_VALUE
- Unbounded demand
-
Complete the request call
sub.____(2);
Show answer
sub.request(2);
Next lesson: Project Reactor Mono