Blocking and Non-blocking

This lesson talks about blocking and non-blocking processes.

Your task

You have to read this lesson and report back here when you are done. Press the button once you are finished. No cheating!

Single-threaded applications

For simple programs, such as beginner-level tasksprinting “Hello World”, we often don’t need more than one thread. However, if we were doing something complex, like running the web server that is hosting this very website, we would be dealing with thousands of concurrent users wanting to access our site. Let’s see how that might look if we were working with a single thread.

Single-threaded applications often get bogged down due to long processes that take time to execute. These processes can cause a block as the application needs to wait for a process to complete before moving ahead.

Multi-threaded applications

We want multiple users to be able to access our website simultaneously. One way would be to have multiple threads, where each thread can serve a single user. Great! Problem solved? Not exactly. Let’s look at the problem again.

Each thread is serving a single user. Whether the user is reading the course or perhaps not generating any requests to the server, our idle thread is still assigned to the user.

Problem solved?

We can serve more users now. However, as we dive deeper into back-end development, we will come across multiple ways of doing the same thing. Efficiency is essential if we want our services to scale well. In our example, we can simply add more computing resources as we need them. While this may seem like a simple solution, it comes at the cost of getting more hardware or computational resources. Let’s see if we can do something more efficient.

Asynchronous processing

This is where Node.js shines. You do not need to wait for the file to be read; instead, you can just ask the OS to work on it and call you back when it’s done reading. Conveniently, asynchronous processes use this very paradigm. Let’s see how that works.

The beauty of Node.js

Node.js applications run on a single thread and are still able to keep up with multi-threaded applications. This is because Node.js takes full advantage of asynchronous computing. It allows a single server to handle multiple clients at once. Processes, such as fetching data from storage or making new connections, can all be performed asynchronously, ensuring that the application does not get blocked. Furthermore, Node.js processes code sequentiallyline by line. Without asynchronous operations, the entire program would halt until a file is read or a setTimeout() is called.

You have read this lesson; time to press that button now!

Get hands-on with 1300+ tech skills courses.