Last updated:
4 min read
What is a worker thread in Node Js and How does it work?
Gathsara Umesh
Author
0%
SHARE

What is a worker thread in Node Js and How does it work?

Worker threads were initially added as an experimental feature in Node.js 10. x.x and became stable in Node.js 12. x.x. Node.js, designed for single-threaded execution, is ideal for handling non-blocking I/O operations. However, it faces challenges with CPU-heavy tasks, as these tasks can cause the main thread to become blocked, hindering the execution of other operations.

In another word when it comes to CPU-intensive tasks, Node executes blocking code in the main thread and blocks other code for execution.

As a solution to this Node introduced Worker threads in Node Js 12 .x.x.

When performing intensive synchronous operations, such as complex calculations on a large dataset, it can severely impact performance. A synchronous block of code that takes a long time to execute can block the rest of the application. For instance, imagine a scenario where a calculation takes 10 seconds to complete. This delay can lead to significant bottlenecks, affecting the system's responsiveness and ability to handle multiple tasks efficiently. Here are three examples to illustrate this issue

  1. Web Server Request Handling
  2. Data Processing in a Background Service

We all know Node js (Javascript) is not meant for this kind of CPU-intensive task. If we do something like this in Node Js it will freeze the UI in the browser and queue any I/O event in Node.js.

Now Let's see how Worker threads are solution for this issue in node js

Worker threads in Node.js are similar to WebWorkers in the browser. Browsers have long used Workers to run scripts in parallel, allowing for multitasking. In Node.js, worker threads provide a way to execute JavaScript code concurrently, enabling efficient handling of blocking operations.

One effective method to prevent a blocking operation from halting the entire application is to run it in a separate thread. By doing so, the main thread remains available to handle other tasks while the intensive operation runs independently. This approach is utilized in Node.js with Worker Threads.

Here’s a clearer explanation:

1. Understanding Worker Threads: Worker threads allow JavaScript code to be executed in parallel, much like how WebWorkers function in browsers. This enables multiple tasks to be performed simultaneously, improving efficiency and responsiveness.

2. Benefits of Using Separate Threads : Running a blocking operation, such as a complex calculation, in a separate thread ensures that the main thread remains unblocked. This means that the application can continue to respond to user interactions or handle other requests while the intensive task is processed independently.

3. Practical Example in Node.js: Suppose you have a Node.js application that needs to perform a heavy computation, like data analysis on a large dataset. If this computation runs on the main thread, it will block the entire application, making it unresponsive. By using a Worker Thread, the computation can run in the background, allowing the main thread to continue handling other operations, such as serving web requests or responding to user inputs.

Now Let's see how node js runs when it's only in a single thread.

When a Node.js process starts, it includes several key components: Single Process: A process is a global object accessible throughout the application, containing information about the execution context.

1. Single Thread: Node.js operates on a single thread, meaning only one sequence of instructions is executed at a time within a given process.

2. Single Event Loop: The event loop is crucial to Node.js's asynchronous capabilities. It enables non-blocking I/O operations by delegating tasks to the system kernel and handling them with callbacks, promises, or async/await. This is how Node.js manages to be efficient despite JavaScript's single-threaded nature.

3. Single JavaScript Engine Instance: This component is responsible for executing JavaScript code within the Node.js environment.

4. Single Node.js Instance: This is the program that runs Node.js code, enabling the execution of server-side JavaScript.

Each of these components plays a vital role in how Node.js operates, ensuring it can handle multiple tasks efficiently while remaining single-threaded.

Now With the worker thread, it's run like this

In contrast, worker threads in Node.js include the following components:

  1. Single Process: There is still only one overall process.

  2. Multiple Threads: Worker threads enable the use of multiple threads, allowing concurrent execution of different tasks.

  3. One Event Loop per Thread: Each thread has its own event loop, enabling asynchronous operations within that thread.

  4. One JavaScript Engine Instance per Thread: Each thread runs its own instance of the JavaScript engine, allowing parallel execution of JavaScript code.

  5. One Node.js Instance per Thread: Each thread operates its own instance of the Node.js runtime, facilitating the execution of Node.js code concurrently across multiple threads.

Node Worker Threds Example.png (Image Source : Internet)

So this is how we can use multi-threading in Node js using worker thread.


LEAVE A COMMENT OR START A DISCUSSION

MORE ARTICLES

Why You Should choose NestJS over other Node JS frameworks🧐

    5 min read

Why You Should choose NestJS over other Node JS frameworks🧐

NestJs

Subscribe to Newsletter

Weekly


  • Never miss an update.
  • Get articles and snippets directly to your inbox.
  • Subscribe to stay connected and avoid getting lost among millions of websites.

Monthly


  • Coming soon...