Sub topic 1
Why reactive? Blocking vs non-blocking request handling
Prerequisites
This chapter assumes Java lambdas and generics, basic Spring Boot and REST knowledge, and familiarity with threads and HTTP request handling.
Blocking and non-blocking handling
In a traditional blocking server, each request usually occupies a thread. When that thread waits for a database or remote service, it cannot handle another request. Under high concurrency, the server needs many threads, which increases memory use and context switching.
Non-blocking handling lets a thread start an I/O operation and return to other work while the operation is pending. When data arrives, the runtime continues the operation. Spring WebFlux uses this model with Project Reactor and commonly runs on Netty event-loop threads.
Reactive code helps most when requests spend significant time waiting for I/O and must support many concurrent connections. It does not automatically make CPU-heavy work faster, and blocking libraries can still stall the event loop.
The Reactive Streams contract
Reactive Streams defines a protocol between a Publisher, which produces values, and a Subscriber, which consumes them. A Subscription connects them and allows the subscriber to:
- request a specific number of values
- cancel the stream
The publisher sends values only within the requested amount, followed by either completion or an error. This protocol provides backpressure, which prevents a fast producer from overwhelming a slow consumer.
Mono and Flux
Project Reactor provides two main publisher types:
Mono<T>emits zero or one value of typeT.Flux<T>emits zero to many values of typeT.
A pipeline is lazy: declaring it does not start work. Subscription starts the pipeline.
Operators and backpressure
Operators transform or combine publishers. map changes each value synchronously. flatMap starts an asynchronous publisher for each value and merges the results. switchIfEmpty supplies an alternative when a publisher completes without a value.
import reactor.core.publisher.Flux;
public class Example {
public static void main(String[] args) {
Flux.range(1, 5)
.map(n -> n * n)
.flatMap(n -> Flux.just(n + 1))
.subscribe(System.out::println);
}
}The subscriber controls the pace by requesting values. Operators may buffer or prefetch values, so configure them carefully when processing large streams.
Exercise
Which Reactor type represents a result that may contain one book or no book?
Show answer
Mono<Book>, because Mono emits zero or one value.