Java Flow API (JDK 9 Reactive Streams) | Publisher, Subscriber, Synchronous, Async, Backpressure, Non-Blocking | Simple Examples

In this article we will go through very basic & simple examples of Java Flow API (java.util.concurrent.Flow) which was introduced in JDK 9. Examples will help to understand different ways in which publisher & subscriber interact to perform desired operations.

Java FLOW API consists of below interfaces which are based on reactive-streams specification.

Lets look at code examples to use these interfaces.

Java Flow API Synchronous

Subscriber takes 100 ms to complete processing. You can see that, when subscriber takes 100 ms to process, publisher is blocked during that time. Next value will be published only when subscriber processing is finished for earlier value. You can also see that both subscribing & publishing happens on same thread i.e. main thread.

Java Flow API Asynchronous

You can see in output that thread names for publisher & subscriber are different. Also publisher is not waiting for subscriber to finish processing. SubmissionPublisher has default buffer of 256, so you can see that till 256 values publisher went without getting blocked i.e. non-blocking. But after 256, since buffer is full, publisher is blocked until buffer is freed up one-by-one.

Java Flow API Backpressure handling (Buffer strategy)

During asynchronous processing, if subscriber is consuming data very slow than publisher, this situation is called as backpressure. There are different ways to handle such situation gracefully. Here is an example in which overflow or backpressure can be handled by buffering values.

As you can see in below output,  till buffer is full i.e. 16 values, publisher was not blocked & publishing of values continued in non-blocking mode. But after buffer is full, publisher started getting blocked until previous values are consumed by subscriber. Buffer values should be chosen wisely so that publisher is not blocked during expected backpressure.

Java Flow API Backpressure handling (Drop strategy)

In this example, we will see another strategy to handle backpressure i.e. dropping values in subscriber is not able to consume values at the speed of publisher. We will also have a handler for dropped values so that appropriate handling can be done. In our example, we just call error handler so that subscriber is aware of dropped values with proper exception & message.

As you can see in output, since SubmissionPublisher has default buffer of 256, values were published till 256 values. After that values started getting dropped. Towards the end of the output, you can see that subscriber only received 256 values & rest of the values were not received because they got dropped.

Leave a Reply

Your email address will not be published. Required fields are marked *