Why Node.js is a single threaded language ?
Applications built on the top of node.js use Single Threaded Event Loop Model architecture to handle multiple concurrent clients like JSP, Spring MVC, ASP.NET, HTML, Ajax, jQuery, etc. are other web technologies that can be used rather than node.js but these listed technologies follow “Multi-Threaded Request-Response” architecture to handle multiple concurrent clients.
Description of the diagram:
n = Number of requests by clients to the Node.js web server.
Lets assume they are accessing our Web Application built on top of Node.js concurrently Clients are Client-1, Client-2 . . . Client-n.
m = number of threads in thread pool.
Web Server receives Client-1, Client-2 . . . till Client-n requests and places them in the Event Queue.
Advantages of Single-Threaded Event Loop over Multi-Threaded Request/Response Stateless Model:
- Can handle more & more concurrent client’s requests with ease.
- Eliminates the need of creating more and more threads, because of the Event loop.
- Applications built on top of node.js use the least threads possible to reduce memory or resource usage.
Reason behind node.js uses Single Threaded Event Loop Model architecture:
- Initially, node.js was created as an experiment in asynchronous processing and in theory was that doing asynchronous processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation when the application isn’t doing CPU intensive stuff and can run thousands more concurrent connections than Apache or IIS or other thread-based servers.
- The single-threaded, asynchronous nature of node.js does also make things complicated but threading is worse than this in terms of time taken to design an application, cost of development, deadlocks, priority inversions, and all the other things that come in the life cycle of an application.
- There is also a very well known and criticized issue with the one thread per request model for a server which is that they don’t scale very well for several scenarios compared to the event loop thread model, in short, they lack scalability as the application grows to meet the future demands and with the addition of new features.