Node is suitable for IO intensive scenarios, not complex computing.
I have studied why Node is relatively fast in processing IO tasks these days, which is recorded in this issue.
Multithreaded server
A traditional multithreaded server, such as a Java server, creates a separate thread for each request it receives. Threads in a Java process share all memory, which means that different threads can share variables created by other threads. This multi-threaded approach leads to the following problems:
- Multithreaded context switching incurs additional overhead and is expensive in high-concurrency scenarios, so the maximum number of concurrent requests supported by a multithreaded server is not high, and once the number of requests exceeds this limit, there will be a blocking phenomenon.
- A deadlock occurs when resources needed by two threads are locked by each other.
- Because multiple threads share memory, they can read and write a variable at the same time, so they need to coordinate the read and write sequence to ensure data consistency.
The node server
Unlike multi-threaded servers, Node servers take a new approach to high concurrency. A Node server process consists of only one main thread and many child threads running in the background. The communication between the main thread and the sub-thread adopts the event message mechanism. When the sub-thread completes the task, it will put the task callback into the task queue and notify the main thread that there are tasks in the queue to be processed. When all the tasks in the main thread are completed, it will turn to the execution of the first task in the task queue.
With node server, all tasks and code are non-blocking, the number of concurrent subthreads in the backend is much higher than the number of threads in a multi-threaded server, and the development process is simpler without deadlocks and data consistency.
The resources
- node js is faster than java
- speaking intelligently about java vs node performance