If you ask, what is Java Script? The answer is: Java Script is a Single threaded, non-blocking asynchronous concurrent language. Now it is important to understand these characteristic of Java Script.

Let’s try to understand, what is Single threaded, non-blocking and what is difference from others.

With other languages, when server receives request, it allocates a thread to fulfill it. As part of handling the request let’s say it queries the database and the thread waits till it gets the response back from database. So it requires new thread to server the another request. If we have large number of concurrent requests then server capacity is most likely to be run out and new requests may need to wait until some thread is available or we need more hardware for more concurrent requests.

Where as in JS (non-blocking IO), it is asynchronous by default. It has single thread to handle all requests. Thread doesn’t wait for the IO (for example DB response) and thread can be used to serve another request. In this example if there is a response from DB then it will be put in Event Queue. Node will monitor the queue and when there is an event in the queue, it will be processed in FIFO order.

This is why Node (btw, node is just a run time environment to run java script at server side) is suitable for I/O intensive apps (e.g. DB read or network access). In contrast, Node shouldn’t be used for CPU intensive apps like video encoding etc.

Before we check this practically, let’s first go through with few concepts:

  1. Call Stack: It is a data structure which records where we are in the program execution.
  2. Callback Function: CallBack function is the function that executes after I/O is done.
  3. Event Queue: It is a queue where events are stored when async call is completed.
  4. Event loop: It is a program whose job is to look at the call stack and the event queue. And if stack is empty it will take first event from the queue and push it to the call stack.

Let’s see how these concepts works in reality. Let’s take an example where there are 3 requests made and let’s assume that each request takes 3 seconds to get the data. In the sequential flow, it would work like below:

But in async flow, it would work like below, where callback function is executed after timeout:

What just happened in the async flow is that, when setTimeout is called (i.e. it is on the call stack), it will be pushed out from call stack to webapis where it will keep the timer and call stack will continue execution of next step. 

Situation when setTimeout is called

Situation after setTimeout is called

Once the timeout is done in the webapis; it will push the call back function to the event queue. 

Situation after setTimeout period is over

And event loop will monitor the call stack and when it is empty; it will push the first event from the queue to the call stack (meaning callback function will execute)

Situation after event loop processes queue

Source link

Write A Comment