How can we implement the Subscriber interface in Java 9?

Java 9 supports to create Reactive Streams by introducing a few interfaces: Publisher, Subscriber, Subscription, and SubmissionPublisher class that implements the Publisher interface. Each interface can play a different role corresponding to the principles of Reactive Streams.

We can use the Subscriber interface to subscribe to the data that is being published by a publisher. We need to implement the Subscriber interface and provide an implementation for the abstract methods.

Flow.Subscriber interface methods:

  • onComplete(): This method has been called when the Publisher object completes its role.
  • onError(): This method has been called when something goes wrong in Publisher and is notified to the Subscriber.
  • onNext(): This method has been called whenever Publisher has new information to be notified to all Subscribers.
  • onSubscribe(): This method has been called when Publisher adds Subscriber.


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

public class SubscriberImplTest {
   public static class Subscriber implements Flow.Subscriber<Integer> {
      private Flow.Subscription subscription;
      private boolean isDone;
      public void onSubscribe(Flow.Subscription subscription) {
         this.subscription = subscription;
      public void onNext(Integer item) {
         System.out.println("Processing " + item);
      public void onError(Throwable throwable) {
      public void onComplete() {
         System.out.println("Processing done");
         isDone = true;
   public static void main(String args[]) throws InterruptedException {
      SubmissionPublisher<Integer> publisher = new SubmissionPublisher<>();
      Subscriber subscriber = new Subscriber();
      IntStream intData = IntStream.rangeClosed(1, 10);
      while(!subscriber.isDone) {


Processing 1
Processing 2
Processing 3
Processing 4
Processing 5
Processing 6
Processing 7
Processing 8
Processing 9
Processing 10
Processing done