Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Reactive streams and backpressure in Java

Reactive streams and backpressure in Java: Java 21 exposes the reactive-streams contract through Flow.Publisher, Subscriber, Subscription, and Processor, with demand controlled by request(long).

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

reactive streams

Java 21 exposes the reactive-streams contract through Flow.Publisher, Subscriber, Subscription, and Processor, with demand controlled by request(long).

Use Flow for an asynchronous pipeline with backpressure when each Subscriber must control its in-flight items; SubmissionPublisher supplies a buffered publisher implementation.

A Subscriber must retain its Subscription in onSubscribe and request items; request(Long.MAX_VALUE) means unbounded demand, and blocking onNext can stall delivery.

A non-positive request terminates the subscriber with onError and IllegalArgumentException; no signals follow one onError or onComplete, and cancel stops demand.

The order onSubscribe, onNext:1, onNext:2, onNext:3, onComplete shows a Subscriber requesting exactly one item after each signal and receiving one terminal event.

Examples

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

public class Main {
    static final class OneAtATime implements Flow.Subscriber<Integer> {
        private final CountDownLatch done;
        private Flow.Subscription subscription;

        OneAtATime(CountDownLatch done) { this.done = done; }

        @Override public void onSubscribe(Flow.Subscription subscription) {
            this.subscription = subscription;
            System.out.println("onSubscribe");
            subscription.request(1);
        }

        @Override public void onNext(Integer item) {
            System.out.println("onNext:" + item);
            subscription.request(1);
        }

        @Override public void onError(Throwable throwable) {
            System.out.println("onError:" + throwable.getClass().getSimpleName());
            done.countDown();
        }

        @Override public void onComplete() {
            System.out.println("onComplete");
            done.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        var done = new CountDownLatch(1);
        var publisher = new SubmissionPublisher<Integer>(Runnable::run, 1);
        publisher.subscribe(new OneAtATime(done));
        publisher.submit(1);
        publisher.submit(2);
        publisher.submit(3);
        publisher.close();
        done.await();
    }
}

Result

onSubscribe
onNext:1
onNext:2
onNext:3
onComplete

The order onSubscribe, onNext:1, onNext:2, onNext:3, onComplete shows a Subscriber requesting exactly one item after each signal and receiving one terminal event.

Sources