Few common misconceptions about node's event loop
As a computer science student, I already had a little idea of different types of languages from my college days. You know, C, C++ etc. Knew about C# as well and used to think that this is an amazing language and I definitely will try my best to work with that in the future.
Yeah, seriously! I mean if you are an average college passout and have only worked with C/C# type of languages who all are synchronous; and someday someone says there is a language which has a single thread and never blocks; you will obviously consider it a magic
Anyway, I eventually read a lot about the event loop from the internet and kind of understood how it works. But unfortunately due to many wrong explanations or very high level view of the same, it created some misconceptions in our (or atleast my) mind.
Today in this article I'm going to highlight some of them. In case you don't know how node.js event loop internally works, you can read that once.
I have not checked how event loops in browsers work, but believe they will be somewhat similar. All my comments below are for the event loop os node js.
Where is the loop?
There is a stack or queue
Myth: To make people understand how event loop works, people often used a stack or a single queue. Seems like every callback, whenever matured is pushed to that.
Fact: First of all there is no stack. And neither there is just a single queue. There are multiple phases in the event loop with multiple queues (other data-structures too) attached in it.
Event loop runs in a separate thread
Some async OS api involved in setTimeout
Myth: The times like setTimeout an setInterval are something handled by some third party, may be OS, who automatically notifies if the time is elapsed and then it got inserted into the queue.
Fact: The reality is, timers are stored in a min-heap memory in sorted order and event loop while going through the
timer phase or
poll phase, check the timer scrips by simple mathematical operation like,
now - registeredTime > delta and executes the callbacks.
setImmediate places the callback at 0th position
check phase or setImmediate phase. Only difference is, after waiting in the
poll phase, the event loop next goes inside the
check phase to execute the callbacks invoked by setImmediate.
Myth: Everything that is asynchronous is handled by event loop which uses a threadpool internally.
Fact: Threadpool doesn't handle every single asynchronous request. If libUV finds that the particular task can be done using OS's asynchronous apis, it uses them. If there are cases where no async api from OS is not available, like file read, dns lookup etc; then libUV uses the threadpool whose default size is just 4 and can be extended using the
UV_THREADPOOL_SIZE environment variable till 128.