First steps with reactive programming in Java

Automatic Summary

An Introduction to Reactive Java Programming

Java programming has expanded its scope and grown immensely over the years, paving the way for new methods of programming, one of them being Reactive Programming. This article intends to get you started with Reactive Programming in Java. So, let's dive deep and dissect what it entails!

What is Reactive Programming?

Reactive Programming is a programming paradigm that treats data as streams that can be observed. It thrives on the principle of 'reacting to changes' in the programming paradigm advent by handling data and event flows asynchronously, thus making it ideal for real-time applications like social networks, mobile applications, and streaming applications. Companies like Netflix are already leveraging Reactive Programming to handle multiple requests efficiently.

Principles and Components of Reactive Programming

At the core of Reactive Programming lies the Reactive Manifesto, outlining five key principles: responsiveness, resilience, scalability, message-driven, and transparency.

  • Responsibility means that the system responds in a timely manner.
  • Resilience is about the system staying responsive despite failures.
  • Scalability indicates how the system remains responsive in the face of a varying workload.
  • Message-Driven highlights how reactive applications rely on asynchronous messages to establish boundaries between components and maintain isolation and location transparency in the application.

Now, let's overview some of the key libraries and components used in Reactive Programming in Java:

  1. RxJava is an implementation for the ReactiveX API in the JVM, which is a library based on the synchronization of event-based sequences.
  2. Reactive Streams is an initiative to provide standards and synchronization for asynchronous flow processing with non-blocking back pressure.
  3. The four primary interfaces of Reactive Streams include: Flow Publisher, Flow Subscriber, Flow Subscription, and Flow Processor.
  4. Project Reactor is a library based on the Reactive Streams specification that enables the creation of high-performance servers.

The RxJava Library

The library deals with observables—streams of data that other parts of your application can observe and react to. RxJava supports sequences and events to compose your event streams in a declarative way.

Components in RxJava include operators like:

  • Map: Transforms items by applying a function to each item.
  • Filter: Omits items from observable that pass a certain condition.

The Reactive Streams in Java

Reactive Streams have been designed to provide a standard and a set of rules for asynchronous flow processing with non-blocking back pressure. It comes with a set of interfaces and methods.

  1. Flow Publisher: Responsible for producing streams and other events.
  2. Flow Subscriber: This interface contains methods for receiving streams and other events.
  3. Flow Subscription: Provides methods for linking publisher and subscriber.
  4. Flow Processor: This interface is responsible for defining methods to handle multithreading operations.

These classes form the building blocks of any Reactive Programming application in Java.

Concepts of Reactive Programming

Some of the key concepts in Reactive Programming include back pressure, streams, reactors, and observables.

  • Back Pressure: Resistance or constraint that restricts the desired data flow through software.
  • Stream: A sequence of objects; can be operated to produce a result.
  • Reactor: An implementation of the reactive streams specification; can emit an arbitrary number of events, including zero.
  • Observable: Can emit multiple data items over time, either a finite or an infinite number of items.

Reactive Programming with Spring WebFlux

Spring WebFlux is a widely-used framework for reactive programming in Java. From Spring Framework version 5.0 onwards, a reactive part was introduced in addition to the traditional servlet-like structure which is represented by the Spring Web MVC.

Spring WebFlux, along with other libraries like R2DBC (Relational Database Connectivity), simplifies and enhances the process of implementing Reactive Programs, particularly by providing support for non-blocking back pressure and the event stream model.

Conclusion

While Reactive Programming comes with its set of challenges, notably the steep learning curve and different error handling methods, the benefits far outweigh the drawbacks. By moving towards non-blocking, asynchronous styles of programming, we can build more responsive, resilient, and scalable applications, making Reactive Programming a valuable asset in any programmer's toolkit.

Whether you're working with Spring WebFlux, the RxJava library, Project Reactor, or any other Reactive Programming tooling available in Java, make sure you understand the essential principles, benefits, and potential challenges to get the most out of your reactive applications.

Embracing Reactive Programming can be a game-changer, allowing you to build more efficient real-time applications with improved performance and user experience. So, get ready to explore a whole new paradigm of programming with Java!

Resources

If you are interested in learning Reactive Programming in Java you can find more information about it in the Reactive Manifesto and the Reactive Streams Specification on GitHub.


Video Transcription

So let's start the presentation. Um Hi, everyone. Today we talk about rif programming Java. The first step is in Rags shift programming Java. I am Pamela Santoli. I am back in developer at Mio.I am also Microsoft CHE EVP and developer techno and comun organizer at the Makers code and peripheral Brazilian tech comin. And I also be book co author of the book journal the Java. So first let's define what is reactive, sorry, reactive, reactive paradigm in the programming paradigm or has to data and event flows as well synchronous because it's like the synchrony is recommended to hand the light alphabet number go measure change in the real time for social networks, uh mobile applications and streaming applications.

Uh The most SU SU is Netflix that has many requests for example. And uh so with the next name case, Rive project is also widely used in social networks for chain and backend because it works orient oriented to user actions uh that result in events. One of the principles of reactive programming, reactive uh paradigm is the reactive manifest. Rive manifest has five principles that are responsibly resilient, ash and message driver response uh means that the system responds in a timely manner. If possible resilience, the system remains responsible to failures.

Alas the system remains responsible in the face of a variable workload. We can have one request or that million requests that systems must uh stay responsible uh last year. And resilient message driven uh reactive applications rely on a synchronous message to establish a boundary between evidences cle conf isolation and transparency in the application. Uh We have some frameworks and libraries in Reif programming, Java. The first is a ex Java ex Java.

It's an implementation for the reactive X stations JVM which uh synchronous an even basis library that works with observable sequence. It extends from the observer pattern. Observer pattern is a pattern that have each object college subject of the pains observers that are automatically not fed to change of the stage through di operators and methods. A X Java supports that sequence and events to compose your event strings. In a declarative way. We have some components in our area X Java and corrective programming. Also the first is a map map transforming items emitted by observable by applying a function to each item. And we have an example of a map operator. For example, we have the observable dot from then have the letters variable, we apply the map function that converts this to uppercase and we have the result for the variable in the uppercase. We have another operator that is come uh to each item and the, and then each, each value co operators, we have another example, for example, we have the array of strings and letter. We have Javn A, we do an observable from letters that makes a scan from this and we hit her in a new screen builder and I paint this in this way, we have another operator that's filter the filter operators amidst all of those items from observable that pass for cage.

And I have another example of the filter operator. Uh We also use the observables. You can see this observable for all numbers. We have a filter of this and made a subscribe it after we finalize, subscribe it in subscription and the reactive strings. That is the base of Java in the reactive programming reactive strings. It's an initiative to provide a standard, a guide and a set of routes for a synchronous flow processing with NIO that is non blocking, push and out, push back pressure rub strings has some interfaces and methods.

The first is the interface flow publisher that contains methods to produce strings and other events in the application. And we have an example of the interface publisher and we have just one method in the interface publisher that is the subscribe. So publisher publish some Evans.

And we made the subscriber from this Avent sheet for a subscriber that we read the information produced by the publisher. And I also have the interface flow subscriber uh this interface contains methods for receiving strings and other events. For the our application in a interface subscriber.

We have four methods we have the unsubscribe that indicates the next that will be done when subscribed in your variable in your class. On next take the next step that we will be done with the result of some item or some action sorry on error in that will be done. We um get some error in the application complete when you finish some action that has found the on action. Also describer we will done some action when we pass this operator this method on complete, we have other other inter description in their interfaces flow of description. We have methods for linking publisher and subscriber. So description is between the publisher that produces some information and the subscriber that reach the rec receive the information from the this publisher design, this data screen uh that is produced by the publisher. The subscription is the connection between these these two objects in the shift programming and the sub description interface. We have two methods. We have the request that you request and use of description between the publisher and the subscriber. And we have the cons method that can sell the subscription. This um this relation between a publisher and a subscriber. You have another interface that the interface flow processor.

The interface flow processor is responsible for the fine methods to do so much advantage operations like transformer items from publisher to subscriber. The processor interface is responsible to make this conversion from uh publisher objection to a subscriber objection to subscriber to publish and other the interface flow uh processor don't have on the any methods this just uh exchange from flow subscriber it and from from flow publisher.

And the last I think the last uh the last class from the reactivity strings is the submission publisher that implements the flow publisher that is a flexible with item producer according to the activity strings, activity strings is a set of rules. That's many rules and many codes and many and operations be uh and then I just uh just bring some of them because this many informations about your activist drinks. This is the simplest way of explaining their activist in the class transform processor. Uh the exchange, the submission publisher and implements the flow processor that were uh explained in the previous and reactive strings. What is the the mission, the objection of the reactive strings? Uh riv strings sustain for runtime environments in the JVM as well as network protocols you can see and the detail of them in the riv screens. Uh JVM github, the main objective of the active strings is to define the exchange of flow data through. And as so our, our the library that use programming and in java or language uh is based on riv strings is a set of rules that our language must follow when you are working with active program, R is programming is the scope to find a minimal set of methods and pa faces and protocols that will describe the operations and is necessary to have a synchronous data flows with NIO that is non blocking, push in and output back press.

And we have some active programming concepts that I talked about observables, publishers to describe it. So now let see what is uh what means each of these uh publishers to describe it and observable and others moment. The first concept is back pressor back presser is the resistance or strength that suppose the desired data flow through the software is a feedback from the receiver to the producer or for the subscriber to the publisher that he is not supporting the load. A string is a sequence of objects that supports various metals that can be operated to produce a result. Uh Three, the link to that source three is capable of amid three events. We have the on X event that have presents some value that go to the next value or next step in a list on the heard that there was an indication that you are on the in the execution on in the case of finish. A indicates that finish at the the list of A or the list of steps of actions, a flux, a flux uh can image from zero to nep rope on X on complete and none. And here we have an example of the timeline of flex from the left to right. So in the example, we can see we have uh six elements, six objects that pass from this operator.

This operator can be a map uh scan another operator that use the new reactive programming. Sorry. This box indicates the transformation that operator performs in the flux. And after path for this operator, these objects have results in a transformation. And we have, if we have some error, then we produce on error in the range of production. And we have the mono and the difference between flex and mono that mono can be emit just the zero from on one event. Uh in the flex, we can emit zero to N events. And mono also can pass from an action complete in a neighbor. And we also have the represent of the measure is not in a high definition. And this is a mono time line from the left to right. We have 11 item issue by a mono that also pass from some operator this box in the transformation that the operator performs in a mono and uchi uh some transformation. If we have some, we have turned on there and we have some uh finish yet, we will have turned on complete some action. After this unobservable, unobservable can pass a message as synchronous a sub describer uh or a receiver. Well, uh as I was saying, uh previous slides consumes the data received from us a description, a publisher uh produces the data that will be the subscription. And a sub description is a connection between subscriber and publisher.

And here we have some example of this uh this flow of this process. We have the publisher that produces some data and send evidence to the subscriber that consumes the data. The back presser is the response of this subscriber. It's not is not able to process this message. For example, we have producing million of of data, many of um million of strings and the subscriber cannot uh cannot read this information. And we use this back presser tools to send this feedback to the publisher to make this good balancer and work with other trades or other alternatives. With this information. A code observable. We have code and hot observable. A code observable is the sequence of events. It's not executed if uh observe observable has an associated and observable uh broadcast. Uh take island of water that is an association area. So is a binary point to point communication protocol tain as in distribution, the applications a static enable the following symmetric interactions model.

Uh Using ay message passing over a single connection, we have a request response. That is a string of one information. A question to string. That is a F string of many I don't have a file for but not have any response. And then did you ever send out strings areas such parts the resumption of the season that allow the resumption of a long term flows in different transport connections. Uh Our R two D BC is the relational database connect shift that brings direct shift programming API to relational database OD BC is also based on the reactive between the specification that uh a set of rules is a guide of reactive programming. R two D BC provides an open specification. So and with R two WC where we can work as swing condos and with NIO uh work with relational database support this call. And finally Spring Web flux. Spring web flux is the most used uh framework about direct shift programming job. Spring web flex can be defined as a parallel version to the very low and widely used the Spring Me DC, the C API and and having as main difference, the support of rgvnio strings and supporting the concept of back pressure with the net server common by the F embedded in the detector in Yle is instead of using the Tom cat and the CLE contained in other component, start to the server API, use the net server.

We have this net server embedded in the architect of spring web flux. But you can also use judge server or uh undertow server spring web flux uh from von 5.0 of the spring framework, we have a reactive part in addition to the serve like structure that already exist. And each model of this is official or you can use the clot part, the part or even both in your application can make a mix of the rive structure and the service structure. Are you out uh out of rive or out of service? This is the stack uh of a spring framework that we have the Servet container that has these components, the Servet API, the spring web MVC and work with controller and request mapping. And in the reactive stack, we have the to catch the judge the N and under to serve. Started off work with the serve with API. We have the att P and reactive strings and started off uh work with Spring Web M DC. We work with Spring Web Flex and start off work with a controller and question map. We can use it with uh H their functions in this uh in this, in that's how we show in the end of this presentation. So and question me flex. I don't use the halter functions because it's uh uh so complicated to change in the beginning of work with spring up flux. So I use all these these components and controller request request mapping.

I made this mix of the, the two weeks Spring Web Flex was developed because we need no non blocking application that could work with a small, a small number of strategy and and that could be run with some source in the server 3.1 an NIO API was provided but uh it's used uh does not correspond to the rest of the API that serve API is blocking.

In your, in your definition, when uh NIO API is uh is the pos position of the service contract. Uh These factors uh were c for the development of a new API that was used in the pain of uh the execution time in a non block. A, it was possible if the service net, for example, or to uh net just and others that consolidated themselves in their synchronous and non blocking operation. Another that uh spring web flux makes it easier to understand the user. The concept of of functional interactive programming.

With the addition of java functional features and the flow API interactive strings in java enable screen web looks to have functional points and author controllers in our applications and how have questions worked. Uh Why does the flow steps for our question is processing in this model is the in the uh spring MC model. The painting on the volume of is the way it was developed can cause a low application and even um out of memory error. This type of error usually occurs when we keep objects for a long time or try to process data. And what steps uh contain the process of request. The user made the request, the request, sorry pass for the server stone catch that has the thread pool pass for the dispatcher Servet pass for the request. My opinion after to the controller after to the services after uh made some database operations again, charter post operations and for finish, return some response on Netflix, we have a different process and we have C data and we have some on action, action action on, on, on complete uh research and returns the data.

And we have the user made some request that pass for the net NIO pass for the E to loop in the net server pass from the R TV screen adapter after pass for the dispatcher Wrangler and after from the functional inch points and return this response for the user, we have a famous and most used library in the reactive programming that I use all my work that is project reactor project reactor is a library based on between the specification.

It is complexly documenting an interactive directed with the function of JVP I using it three in duration and computable feature for composing using flux and mono in micro CS offering back pressure mechanisms RD for TCP UDP and ATT P including web sockets. Uh If the papers and Shaler can support a large transfer volume of aptitude, then medium requires per second. According to reactor documentation, it was also the first to act to the library by the directive strings of applications which are later. Uh I was implemented by EJ two uh uh reactor models are abstracted and interoperable flows to F and can be used with spring frameworks drivers and clients, for example called Foundry Java client in protocols. Uh some for example, where should ABC and the direct socket that uh were explained in the previous slides, we have the three components and the reactor, we have the reactor car that is the main part of the library. The other models depending on the reactor car, the actor car provides reactive types that implements a publisher that provided flus and model reactor edge is the server for our NIO application user for development high scalable servers. And now it has some change my screen but other screen just a moment. Let me check. All right, let me just increase the size of the ladder. So this is a very simple example of reactive programming. I will explain what the pains I use in here.

And what steps I use for invade this crude using web websites. So what's different for a spring web flux application from a spring on VC application? First is the pens, for example, start of using the springy starter web. If I not forgot we using the springy boot starter web flux that contains the night in bed. The other factors instead he often use it. Um uh How can I say uh blocking a driver for database in this application using Mongo DB in a Docker container that is already running. I use a reactive driver for Mongo DB that for our databases. I think we have a reactive driver driver. So we have this data dependence, the spring boot starter that among the V reactive are the pains that is, is close of spring web flex is they spring the dock up. We have the spring for spring and when we using spring web flex, we need to use the spring doc open NP I web flex U I for tests. Uh We have this embedded reactor test that has a start testing reactive applications. So let's go see the coach. Uh First let's talk about the model. The model uh doesn't have many different far as bring M DC example. Uh Now, here we have a, a class that's a model, a table of speakers that have the fields ID name and stack.

We have some constraints here and now there is the repository in repository. We have some difference. For example, we exchange from the reactive mango repository that have some methods that have insert to find out and others methods, a reactive mango reposit ex from reactive certain repository and also extends from the reactive, acquired by example as a cutter. Uh You, you always see the directive a word in the this dependence and the, the class that has some details that I need to explain to the controller. Uh Here I am using rash controller that uh is part of the S API I make this mix. Uh in my work, I use a uh R controller instead of halter functions but using web flux. So I can use this uh Starlet and web flux uh in the same time. So let's talk about the structure of this class. We have the flux in the model. For example, when I have a point that uh return our speakers, that is a speaker group, that our speakers, how I uh I am using zero to N speakers. Many speakers in this, in this point we work with a flux. Uh is when, when I use a post that I just creating one speaker. Uh I use a mono when I'm getting, getting my ID, that I just return one speaker out. So I am using mono delete. I also use a model.

And when I work with strings that uh return the data in other formats that not is uh J zone is other format. We work with a flux because it's a flux of various speakers. Let's see if this demo is working. I have some minutes. So the end. Yes, working. OK. I think I don't have a speaker created. I share the postman screen now. OK. So let me change this screen. OK. Here we have the postman. The application is running in another window here. Let's try to create some speakers and get the speakers uh request. It's a post, the body a part radiating. Let me check the fields names. We have a name in the right. Nay Camila. And the ST is, yeah, let's see if it works. I hope that works. Oh And the request. 0 uh 86 P. Uh Not found. Let me check. OK. Hi speaker. Not try again. Yes, I created the new speakers. The ID is also generated with the name Camille. So I call this, this, this is the create end point. That is a mono because we just CRE create uh one speaker. Let's get the speaker speaker. Sorry. Right. Tr let's send the request. Let's create other speakers. Let's try to find by ID D ID is working. I will share interpret if you um on the end of events uh get but on the lead, let's try the delete endpoint. OK. Uh That's great. Other, just to show how a string returns the information, women, text speaker. OK. Right. Right. Let me check. What's the end point of string? Remember that is a flux of screen. We have uh various uh speakers, threes of speakers. Let me try oh speaker.

But the difference between a get using J zone and using a string is that in J zone? Um I change this. Let me get this ID to bring the other speakers in Jason. We have the data return in this way with this Jason format and when you using I string and the return in other formats, let me check you. And how can uh not, not shows uh the response uh come with this data on the beginning and have this other formats of response that has the same. Um But this is a way to to show what uh contains in the string in string is the main component of active programming than just for curiosity and show you how uh ari of the strings, another type of return oh sorry uh strings. Uh don't work with application Jism. And that is this another type text even. So let me return to the presentation, right? Uh Just uh remember that spring starter, flex and spring boot starter. That among the B reactive in this repository, the main difference that uh extends from reactive among the B repository in the points. The difference and the of uh using response are just uh the name of some response class we must pass.

And that uh if they return the response of this in points will be a flex or a mono. What are the benefits of rift programming? Rift programming is non blocking which generates a certain performance gain. Uh works programs works with fewer rights. So let's use it and spend memory. Um interactive programming follow the principles of the reactive manifest. Just uh remember uh responsibly resilient to last and message driving applications and one of the problems cause nothing's perfect. The problems is a different form of programming.

Uh Is that the qualitative way of programming uh uh mainly if you use um h their functions, you would see many difference from the normal way of programming. Java. And you need to learn other forms of work. You need to learn how the space of reactive programming when you are working with web flex. So sometimes we don't have uh sufficient time to learn a new part in the work or other situation. So it's a problem of rive programming, in my opinion. Another problem is the, the way of the air horse are informed because the, the bugging in the stack tracing of the spring web flux is many different of spring MVC. So it's another problem, you need to learn how to channelize uh air horse and stack races in another way. But uh other, other topics is just benefits using sprint web plus. Uh Here I have with some he that I use in this, this presentation, I will share the slides with the organization in my social network after this. And here we have the my linkedin profile and my Twitter profile. Feel free to connect you to talk about reactive programming or other talk. And thanks for acting and thanks for the opportunity to stay here.