Skip to content Skip to sidebar Skip to footer

What Are The Advantages To Blocking Code Over Non-blocking Code?

I'm learning about JavaScript and Node. I understand how asynchronous stuff works. I get why it could significantly speed things up. I see that other languages (like Ruby and Java?

Solution 1:

Blocking, or synchronous code is easy to write, and the default single threaded behavior. When each task depends on the next, then blocking code makes sense. Before multi-processors and multi-threading, this was the only available alternative, historically.

Non-blocking, asynchronous, multi-threaded programming was created to improve performance in the case where more than one task could be performed in parallel. This improves performance, but at the expense of adding complexity, making code maintenance more difficult.

Solution 2:

It is first worth noting that javascript will almost never allow you access to multiple cores. Therefore you will not (generally) see speed gains from non-blocking code. This is one of the primary benefits of nonblocking code in other languages. In javascript asynchronous code is generally used to handle events (such as a users input, or a file download) where you would not want to halt everything and wait for the event because it may take a while (or never happen). The primary disadvantage of asynchronous code is code complexity. Whenever you write asynchronous code you need to watch out for two threads messing with an object at the same time etc.

Solution 3:

There are also blocking JavaScript runtime environments, like RingoJS or early Node competitors. Blocking code has advantages if it's long-running and cannot be split up into different parts. If you can't rely on non-blocking IO as your basic scheduling interval, blocking might be a better solution.

Just think about the following scenario: Your incoming requests are not some KB of content, they are hundreds of megabytes. And your code reads all the incoming bytes in one go. If you parse such requests in an event loop, it will block all the other requests in the queue, which have to wait for processing. Blocking runtime make this easier, since a thread might be pulled from the CPU and another thread continues to work on his large input, but both are active in parallel.

The real problem in blocking environments is shared state. If a lot of threads have access to the same variable, synchronization is needed and this leads to a lot of wasted resources. It's like blocking the event loop in non-blocking environments: Just don't do it.

Personally I find blocking code easier to read and understand, since it follows one line of execution and has no callbacks or futures. But it depends on the problem you want to solve. Both sides have pros and cons in various scenarios.

Post a Comment for "What Are The Advantages To Blocking Code Over Non-blocking Code?"