Reactive Programming in Java: How, Why, and Is It Worth Doing? Node.js
Node.js
The idea of Node.js is that JavaScript is transferred to the server-side, and all I/O operations become asynchronous. Instead of blocking a thread, for example, when addressing a file, we get asynchronous I/O. Addressing a file becomes asynchronous too. For instance, if a thread needs to get file content, it says: “Please give me file content, and once it is read, call this function.” We have set a task and continue working.
Such an asynchronous approach turned out to be quite effective, and Node.js quickly gained popularity.
How does Node.js work?
There is a receiver at the input, it’s a cycle. JavaScript a single-thread language. But that does not mean you cannot do anything in other threads. It supports threads via Web Workers, etc. But there is only one thread at the input.
Computational tasks for Node.js usually are tiny. The central part of work is input/output (to the database, file system, external services, etc.). Computations take a short time. Once data is received from the database or file system, a callback function is invoked, i.e., some function to which data are passed.
But there is no wait in this scheme. Let’s compare it with a traditional model of a multithreading server in Java.
What happens in Java?
There is a pool of threads. At first, the call gets to the first thread, then some thread is blocked, and we create another one. It’s blocked too, and we create the next. They are blocked because they are addressing the blocking I/O operations. For example, a thread requested a file or data from the DB and is waiting for this data to arrive.
The Node.js model quickly gained popularity. Naturally, people then started rewriting it in other languages. At some point, Node.js took the lead in highly loaded systems with a large amount of I/O operations. But it’s not suitable for any system. If you have many computations or a small number of requests, you won’t see a great advantage. Therefore, there started to appear similar solutions in Java, including a platform for asynchronous I/O – Vert.x. Vert.x server is based on the same principle as Node.js.
Node.js is an interesting solution. It really helps increase performance. When reactivity arrived, they started using a server called Netty. This approach provided a lot of benefits.