Macro-fusion

Macro-fusion mostly occurs during assemble time and its aim is to replace one operator with another. For example, we have already seen that Mono is highly-optimized for processing only one, or zero, elements. At the same time, some parts of operators inside Flux are also supposed to process one or zero elements (for instance, the operators just(T), empty(), and error(Throwable)). In most cases, these simple operators are used along with other transformation flows. Consequently, it is crucial to reduce such overhead. For that purpose, Reactor provides optimization during assembly-time, and if it detects that upstream Publisher implements interfaces such as Callable or ScalarCallable, the upstream Publisher will be replaced with an optimized operator. An example where such optimization will be applied is the following code:

Flux.just(1)
.publishOn(...)
.map(...)

The preceding code show a really simple example where the execution on element should be moved to a different worker right after the element is created. In case if no optimization is applied, such execution allocates a queue for keeping  elements from the different worker, plus enqueuing and dequeuing elements from such a queue causes a few volatile reads and writes so execution of such plain Flux casts too much. Fortunately, we may optimize that flow. Since it does not matter on which worker execution take place and supplying of one element may be represented as a ScalarCallable#call, than we may replace publishOn operator with subscribeOn which does not require creation of an additional queue. Moreover, the execution of the downstream will not be changed because of applied optimizations so we will get the same result from running optimized stream.

The preceding example is one of Macro-fusion optimization hidden in Project Reactor. In Assembly-time section of this chapter we mentioned another sample of such optimizations. In general, the purpose of Macro-fusions applied in Project Reactor is optimizing assembled flow and instead of using a powerful tool just to hammer a nail, we can use a more primitive and less costly solutions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.128