Question

I've two noob questions:

1) Why node.js is being run in a single thread? why not it just uses the process itself? OR What are the advantages of running it in a thread instead of process?

2) What happens if a thread in a process crashed (I am aware that, un-handled exception will cause process to exit), but what happens if its properly catch'd ? or with exceptions like Floating point exceptions. will the process also crashes?

Was it helpful?

Solution

I think you're a bit confused about what "single threaded" means in this case. Node.js itself utilizes multiple threads in the background to handle otherwise blocking calls in an asynchronous manner.

Node.js core, the JavaScript engine, is single threaded. The lack of multi threading and the availability of an event loop makes programming a whole lot easier. In short, you don't have to deal with all the concurrency issues that multi threading brings with it your code is a whole lot more deterministic this way.

In case a thread crashes it's completely irrelevant whether this was the only one or one of many, if code crashes the best thing you can hope for is that the program dies with it, nothing would be more troublesome than having you program continuing to run with partly corrupted state. Imagine the thread that crashes was responsible for saving data to disk, and now you program continues to run without ever saving again.

OTHER TIPS

  1. node.js is designed to be extremely lightweight, and is only called when needed. So each thread handles one request then exits. You if you call /mypage, node.js will process the request and then will terminate. This results in better performance while keeping a small footprint
  2. If there is an exception, and it is properly handled, then it will throw an error according to how you defined it. Javascript is all or nothing language. Any error will cause javascript to throw an error and crash, thats why you need to make sure you handle all possible errors.

Running a program in a process or single threaded is the same thing. Every process has a main thread. Depending on the programming language and platform, additional threads can be used to run parts of your program concurrently. Node.js doesn’t have a possibility to start additional threads.

This way, you don’t have the possibility to run pieces of your program in parallel besides starting new processes. Multiple threads in a single process share the same memory, while processes don’t. When you need to share information between processes, you have to use message passing.

The disadvantage of message passing is that it is slower than sharing information through memory. The advantage is that you don’t have to reason about mutable state of the objects in your memory and how to ensure that those objects don’t become inconsistent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top