King Java had a dream last night.

In my dream, there was an old man with a white beard, who was full of fairy tales, and told him: “You Java ah, it is too weak, even a basic function can not achieve!

The king was surprised: “What function can’t I do with Java?”

The old man showed two lines of code:

float salary = 1000; Float tax = salary * 0.1;Copy the code

The king said, “Isn’t it very normal? The salary is 1,000, and the tax is 100. Every schoolboy in our country can figure it out.”

The old man said, “If I salary=2000 now, how much tax would that be?”

“Still 100! Because the tax is not being recalculated!”

“Salaries have changed, so why not taxes?”

“This……”

When the king stopped speaking, the old man continued, “You have to make a correlation between the variable tax and the variable salary, and make them like Excel. When one cell changes in value, Excel’s formula will update the other cell and make it change.”

float salary = 1000; Float tax <= salary *0.1salary = 2000; float tax <= salary *0.1salary = 2000; assertEquals(200,tax); // Tax now automatically changes to 200Copy the code

The king said, “What’s the use of doing that? Besides, it’s not Java, all languages have this problem…….”

The old man made no answer and slowly disappeared.

The next morning, the king told his ministers about his strange dream and asked if anyone could explain it to him.

This is strange, is there a god deliberately give people dream? In their dreams the old man gave them all the same examples.

The assembly minister said carefully, “Is he implying that taxes in our country are too high, 10 percent, and should be lowered a little bit?”

The king glared at him. “What nonsense? Our tax is not high at all. The threshold has been raised to 5,000 yuan. In addition to the five social insurances and housing fund deduction, we also have a series of policies such as mortgage deduction, rental deduction, one-child deduction and old-age support deduction.

The assembly minister made a hasty silence.

The IO minister continued: “Don’t worry, your Majesty. Java has already provided a solution to the old man’s problem, which is the publisher-subscriber model. If Salary is regarded as a publisher of data source and Tax is regarded as a subscriber, register in Salary and send an event to Tax whenever Salary changes. After Tax receives it, it is ok to do the corresponding calculation.”

“It’s just a model of constantly pushing data out to an observer or a subscriber. What’s the point of that?” “Said the old minister of thread.

“It doesn’t really work in this scenario, but this kind of flow of events, if handled properly, can solve big problems.” IO minister although not quite convinced, but also can not come up with any good application scenarios.

When the king saw the two old guys getting back to work, he quickly changed the subject and said, “I hear we’re having a bit of a problem with high concurrency in Java?”

IO minister immediately excited, followed the rod to climb: “Yes, for more than 20 years, our Java has been using the Tomcat type of thread pool, and now it is getting worse and worse, difficult to cope with high concurrency.”

This suddenly brought in minister Tomcat, Minister thread, and even Minister Servlet, and the king secretly regretted it.

The IO minister continued: “The current model has a thread for every request that comes in. If the request involves IO or network operations, the thread has to block and wait, and can’t do anything else.”

“If users make too many requests, the thread pool will run out of threads very quickly. There is no way to provide services.”

That’s true, and that’s how the servlet-based threading model works.

The king asked, “Why did that thread wait when it called the RPC service? Why don’t you let it do something else, like handle another request?”

“That’s the point, your Majesty, is to make the most of threads. You get an IO call at one point, you walk away, you do something else, and when the IO call is over, you tell the thread to do it, so we can do a lot of concurrency with a few threads.”

The king said, “You have a point. You can already do this NIO, right?”

“That’s right, now all we have to do is transform Tomcat, transform and even replace servlets!”

As soon as minister Servlet heard this, he was anxious. He was the traditional way of working, one request and one thread. If he did this, his position would be lost, and he turned his eyes to his loyal ally, minister Thread.

Thread minister understood: “The solution of the IO minister is to change the synchronous blocking call to asynchronous non-blocking call, which is not so easy ah, among other things, this asynchronous programming, for our subjects is not easy.”

“Don’t you have some Future, Callable thing? The people can use it!” The minister of IO insisted.

The thread minister laughed: “You only know one thing and you don’t know the other. When you call the future.get(), if the thread hasn’t finished its work (such as database query), the current thread will have to wait and still block.”

IO minister a little regret, how did he ignore this layer?

“And even if all operations are asynchronous and event-driven, as you said, callbacks are a lot more common. Have you considered the callback hell problem in this code?”

fun1(param,new Callback(){ void onSuccess(...) {... Execute the business logic...... fun2(param,new Callback(){ void onSuccess(...) {... Execute the business logic...... fun3(param,new Callback(){ void onSuccess(...) {... Execute the business logic...... fun4(param,new Callback(){ void onSuccess(...) {... Execute the business logic...... } void onError(...) {}}); } void onError(...) {}}); } void onError(...) {}}); } void onError(...) {}});Copy the code

IO minister to see this as a mess of code, the head of a big hum, this asynchronous operation incredibly so abnormal!

The king saw that the IO minister looked different and said no more, and immediately announced his retreat.

In the court very depressed minister IO angrily returned home, the tea served by the servant was also knocked to the ground by him.

The staff, already aware of what happened at court, came forward and said, “The adults are quiet, but the Reactor has heard that there is something called a Reactor that uses a stream of events and higher-order functions in functional programming to solve this callback hell problem.”

Event stream? The minister of IO suddenly woke up. Why didn’t I remember this stubble? Yesterday the fairy told me to dream and guided me to use events to flow?

“How exactly?” he asked quickly.

“We have a graph, a stream of events that looks like this, and in this timeline, we have Error events and Complete events, which are Error events and Complete events, which I won’t draw.”

“Yes, but what good does it do?” Asked the Minister of IO.

“You can use functional programming to transform the event stream, such as map, from ‘circles’ to’ triangles’.”

“You can also use filter to filter the event stream.”

“Well, it seems pretty clear. I can think of a scenario where I call function 1, which generates a stream of events, and then I call function B for each element in the stream, which generates a new stream of events. What do I do?” Asked the Minister of IO.

“Your excellency is really fierce, abstract thinking ability extremely high!” “This is the time to flatmap new events.”

“Map, filter, flatMap are just the most basic operations, switch, take, merge,zip and many more operators, you can do everything you want!”

“Yes, yes,” said the Minister of IO, rubbing his hands excitedly. He had grasped the key idea, and callback hell could be solved.

Call fun1 asynchronously and call fun2 based on the result of fun1.

fun1(param,new Callback(){ void onSuccess(...) { fun2(param,new Callback(){ void onSuccess(...) {... } void onError(...) {}}); } void onError(...) {}});Copy the code

Now suppose fun1 returns a data stream, and fun2 returns a data stream. In this new way, it can be written like this:

fun1(param).flatMap( e -> func2(e)).subscribe(r -> showResult(r),       error -> handleError(error));Copy the code

Flattening the series of retractions!

The minister of IO asked, “What was the name of that software you just said was civilian?”

“There are a lot of people, RxJava, Reactor, do you want me to call in their principals for a chat?”

“Wait, this Reactor alone is not very useful, you bring in the Spring chancellor, we need Spring to use the Reactor, ditch the servlets, and make all requests and processes asynchronous!”

Three months later, the Minister reported to the king, “Your Majesty, I have solved the dream entrusted by the gods, and it is actually enabling my Java empire to achieve Reactive Programming!”

“Reactive programming? It’s a strange name!”

“Yeah, it’s event-based and functional programming, and it allows us to handle requests in a non-blocking, asynchronous way, and get rid of callback hell.”

Minister IO told the Reactor to the king.

“How does this Reactor work?”

“Your Majesty will remember that we have Java’s high concurrency problem, which is caused by our inability to effectively manage asynchrony and callback hell. Now, I and Spring have worked together to create something called Spring WebFlux, dedicated to your Majesty, which does not use servlets, can implement non-blocking IO, and can effectively deal with high concurrency. ” The IO minister showed a picture.

Minister Servlet looked and turned green. Where is my place?

Tomcat minister also feel uncomfortable, the original one alone, now Netty to squeeze out.

Only the JDBC minister is not in a hurry: “Processing everything with asynchronous non-blocking? You save, I access the database here or blocked!”

IO minister heart dark call is not good, how forget JDBC so important things, since want to achieve asynchronous, non-blocking, it must be end-to-end, full link implementation, a point of blocking call will lead to the whole problem.

But he remained calm: “Don’t worry, the civilian open source community will soon come up with a non-blocking JDBC driver.”

The king saw that the new Spring WebFlux was going to change the lives of several big people, so he had to appease Tomcat, Servlet: “Well, new things have to have a gradual adoption process, so let’s let Spring MVC and Spring WebFlux coexist for a while and let people choose according to their actual situation.”

Postscript: this article appeared in the example comes from: http://blog.leapoahead.com/2016/03/02/introduction-to-reactive-programming/, I did.

About old Liu and code farmer turn over

I’m a thread

I’m a Java Class

Object-oriented Bible

TCP/IP daming postman

CPU forrest gump

Principle of load balancing

A story over HTTPs

The pinnacle of programming languages

Java: The Birth of an Empire

JavaScript: A loser’s counterattack

C language: When I returned home for the Spring Festival, I found that I was the only one without a date