Reactive Streams (Flow API)
2 mins
Java 9 introduced the java.util.concurrent.Flow API, which provides a standard for asynchronous, non-blocking backpressure in reactive streams.
Source Code #
The Flow API Interfaces #
The Flow API consists of four main interfaces:
- Publisher: Produces elements and provides them to subscribers.
- Subscriber: Consumes elements and signals demand via backpressure.
- Subscription: The “link” between a publisher and subscriber.
- Processor: Acts as both a subscriber and publisher (e.g., for mapping or filtering).
public interface Publisher<T> {
void subscribe(Subscriber<? super T> subscriber);
}
public interface Subscriber<T> {
void onSubscribe(Subscription subscription);
void onNext(T item);
void onError(Throwable throwable);
void onComplete();
}
public interface Subscription {
void request(long n); // Request elements from publisher (Backpressure)
void cancel(); // Stop receiving elements
}
Canonical Usage #
When to use: Use Flow when you have a stream of events or data that must be processed asynchronously by multiple consumers, and where the producer should be slowed down if consumers are overloaded (backpressure).
Common Patterns:
- SubmissionPublisher: The JDK’s default implementation of
Publisher, which can be used to “push” items to any number of subscribers.
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
// Add a simple subscriber
publisher.subscribe(new MySubscriber());
// Push an item to all subscribers
publisher.submit("Reactive Item");
publisher.close();
Performance Considerations #
- Pros: Standards-compliant reactive processing. Built-in support for backpressure. Efficient multi-subscriber distribution.
- Cons: High conceptual overhead compared to simple queues. Only useful for truly “streaming” data.