javascript - event driven and concurrency issues?

Greetings,

I've been studying javascript, nodejs. And I don't understand how the concurrency issues are avoided in javascript.

Lets say I'm working on a object

var bigObject = new BigObject();

and I have a setTimer(function(){ workOnBigOjbect...} ) that will also do work on bigOjbect.

If I have disk IO being written into bigObject, and a timer object working on bigObject, and regularly code reading from bigObject, how are concurrency issues avoided?

In a regular language, I would use a mutex or thread-safe queue/command pattern. I also don't see much discussion about race conditions for javascript.

Am I missing something?

Answers:

Answer

The whole point of node.js is that it's event-driven. All the code runs in event handlers in a single thread. There are no concurrency issues because the code doesn't run concurrently. The downside is that each event handler must exit quickly because it blocks the other events.

In your example, the code will start the disk IO and exit immediately. The node.js infrastructure will notify the program that the IO operation was completed by running an event handler. The timer event will be called before or after the IO event, but never concurrently.

Answer

Javascript is single-threaded. If the time arrives when your function is supposed to execute (based on how you called setTimer), and the parent code is still running, the function will not execute until the parent code has completed.

Answer

There is only a single thread; see: Node.js on multi-core machines

I would speculate that this is because Multiple threads are not supported in the underlying V8 JavaScript engine since typically JavaScript executes within a browser (where in a windows case there is only a single UI thread) and does not support multiple threads.

Answer

There's is this thing in javascript called Run-to-Completion which ensures that if a code is executing it executes completely before any other (asynchronous) code runs, hence, no concurrency issues.

In case of your example whenever the timer callback is called it will execute completely and will never be pre-empted in middle to execute some other code.

See Why no concurrency control tool in javascript for more details.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.