Wednesday, 21 January 2015

Event Loops in JavaScript (Multiple processing with single thread)


Introduction

In most of the languages for concurrency there are multiple threads, each concurrent process needs to be assigned to each thread and responsibility of the developer is to maintain deadlock, racing condition and all those dirty threading related stuffs among these threads.

Q & A

Q: Then what is different in Javascript?
A: It has only single thread.

Q: ohh! Then how to manage concurrent tasks with a single thread?
A: That is an “Event Loop Model”.

Q: What is an “Event Loop Model”?
A: To understand it first need to know Javascript memory processing model.

Q: That means JavaScript has a concurrency model based on an "event loop"?
A: Yeah!

Q: But how single thread…hmmm getting confused.
A: In JavaScript, almost all I/O is non-blocking. It includes HTTP requests, database operations and disk reads and writes. The single thread of execution asks the runtime to perform an operation, providing a callback function and then moves on to do something else.
When the operation encountered an event, a message is enqueued along with the provided callback function. At some point in the future when main thread complete it’s work the message is dequeued and the callback will be fired.
Q: I am not clear with what you are saying?
A: Ok! First just understand the memory model for the JavaScript.

Memory Model

Let see the below model->

What Fits Where?
Stack: All the function are allocated to stack and once the function complete it’s work and return back, that particular stack frame popped up.

Heap: If we create any object of javascript that object is created on Heap having a link to its function which is in stack frame.

Queue: A JavaScript runtime that contains an event queue, which is a list of events to be processed. The each event is associated with a callback function.
When the “Stack” is empty, event is taken out of the queue and processed.

Understand Processing Model

  1. Add functions to stack.
  2. Run To completion.(Execute stack frames)
  3. Add events to event queue if any event encountered during processing of stack frame functions.
  4. When the main stack become empty.
  5. Create stack for “callback functions” in event queue.
  6. Run to completion for newly created stack.
  7. If any new event found in newly created stack step 3 will be repeated.

Let us analyse execution steps for above example

  1. We call the function Func1(), so it will be put on stack at first position.
  2. While processing Func1() a new method encountered “Func2()”
  3. A new stack frame is created and pushed above Func1() inside stack memory location.
  4. Now Func2() start its execution.
  5. During Func2() execution ,Func2() encountered with first event having a callback function.
  6. Now JS put this event on event Queue with its callback.
  7. Later on one more event is encountered so JS placed it also in event Queue.
  8. Function Func2() execution completed and stack frame for it will be popped out.
  9. Now it will start executing Func1() from where it previously jump out.
  10. Stack frame for Func2() also popped.
  11. After main stack will be empty, event queue events processed and callback functions Func3() and then Func4() are pushed in stack 
  12. First Func3() will be processed and then after Func4() .

Analyse from below snapshot what we have learn so far




Summary

  1. Javascript has only single thread.
  2. To perform concurrency it has Event Loop Model.
  3. It follows Run to completion & Adding Events to Queue.
  4. No dead lock no racing can be encountered.
  5. Just pass all the functions as callback to the event queue.
  6. All the I/O can be async with a single thread.
  7. Overall a never blocking model is attained with only one thread.
  8. Inside setTimeout, time given by us is minimum time to process the request and not the exact time.

1 comment: