Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs callback mechanism - which thread handles the callback?

I'm new to nodeJS and was wondering about the single-instance model of Node. In a simple nodeJs application, when some blocking operation is asynchronously handled with callbacks, does the main thread running the nodeJs handle the callback as well?. If the request is to get some data off the database, and there are 100s of concurrent users, and each db operation takes couple of seconds, when the callback is finally fired (for each of the connections), is the main thread accepting these requests used for executing the callback as well? If so, how does nodeJs scale and how does it respond so fast?.

like image 785
Some guy Avatar asked Aug 06 '13 13:08

Some guy


People also ask

How does Node handle callback?

For example: In Node. js, when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.

What is a thread pool in node js which library handles it?

In Node, there are two types of threads: one Event Loop (aka the main loop, the main thread, event thread, etc.), and a pool of k Workers in a Worker Pool (aka the thread pool). The libuv library maintains a pool of threads that are used by node.

How does NodeJS thread work?

Node. js runs JavaScript code in a single thread, which means that your code can only do one task at a time. However, Node. js itself is multithreaded and provides hidden threads through the libuv library, which handles I/O operations like reading files from a disk or network requests.

How does node js handle concurrency given it's single threaded?

The reason why node js is popular despite being single-threaded is the asynchronous nature that makes it possible to handle concurrency and perform multiple I/O operations at the same time. Node js uses an event loop to maintain concurrency and perform non-blocking I/O operations.


1 Answers

Each instance of nodejs runs in a single thread. Period. When you make an async call to, say, a network request, it doesn't wait around for it, not in your code or anywhere else. It has an event loop that runs through. When the response is ready, it invokes your callback.

This can be incredibly performant, because it doesn't need lots of threads and all the memory overhead, but it means you need to be careful not to do synchronous blocking stuff.

There is a pretty decent explanation of the event loop at http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/ and the original jsconf presentation by Ryan Dahl http://www.youtube.com/watch?v=ztspvPYybIY is worth watching. Ever seen an engineer get a standing ovation for a technical presentation?

like image 75
deitch Avatar answered Nov 23 '22 23:11

deitch