Reactor Pattern is used to avoid the blocking of the Input/Output operations. It provides us with a handler that is associated with I/O operations. When the I/O requests are to be generated, they get submitted to a demultiplexer, which handles concurrency in avoiding the blocking of the I/O mode and collects the requests in form of an event and queues those events.
There are two ways in which I/O operations are performed:
- Blocking I/O: Application will make a function call and pause its execution at a point until the data is received. It is called as ‘Synchronous’.
- Non-Blocking I/O: Application will make a function call, and, without waiting for the results it continues its execution. It is called as ‘Asynchronous’.
Note: Node.js is Asynchronous in nature.
Reactor Pattern comprises of:
- Resources: They are shared by multiple applications for I/O operations, generally slower in executions.
- Synchronous Event De-multiplexer/Event Notifier: This uses Event Loop for blocking on all resources. When a set of I/O operations completes, the Event De-multiplexer pushes the new events into the Event Queue.
- Event Loop and Event Queue: Event Queue queues up the new events that occurred along with its event-handler, pair.
- Request Handler/Application: This is, generally, the application that provides the handler to be executed for registered events on resources.
How Reactor Pattern works?
- Everything starts with the application. It makes a request and the event demultiplexer gathers those requests and then it forms queues know as Event Queues.
- In the diagram above, there is only one event queue and there are 7 basics queues. Those queues have ascending priorities, the queue that has the highest priority is checked first by the event loop.
- The Timers queue has the highest priority. setTimeout and setInterval functions are queued here. Once the events are done in this queue, or time is up, the event loop passes those functions to call stack, named as executing handler.
- When one of the event queues is complete, instead of jumping to the next queue, the event loop firstly will check the other two queues which queue other micro tasks and process called nextTick functions. Then it will jump to the upcoming queue.
Callback queue is an event queue and call stack is execute handler.