Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a concurrent read/write read/write collision in JavaScript in the browser?

I have a situation where I am making several (say four) ajax calls (using AngularJS http get, if that matters) and I want each call to callback and increment a counter, so I can know when all (four) of the threads have completed.

My concern is that since JavaScript does not have anything comparable to Java's "synchronized" or "volatile" keywords, that it would be possible for multiple concurrent threads to collide while incrementing a counter, thereby missing some increments.

In other words, two threads come at the same time, and both read the counter, getting the same value (for example 100). Then both threads increment that counter (to 101) and store the new value, and behold, we missed a count (101 instead of 102)!

I know that JavaScript is supposed to be single threaded, but there are exceptions.

Is this situation possible in the browser, and if so, is there any way to guard against it?

like image 539
Victor Grazi Avatar asked Jan 11 '15 05:01

Victor Grazi


People also ask

How does JavaScript handle concurrent work?

JavaScript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java.

Is map thread safe JavaScript?

There are also thread-safe implementations of map() and reduce() and a public method allowing a program to temporarily lock out writers.


1 Answers

No, it is not possible (no collision will occur). Each AJAX call response can be considered a message on the JavaScript message queue. The JavaScript runtime processes each message on the queue to completion before processing the next. In other words, it calls the callback for the event and runs the full callback function (and all the functions it calls, and so on) to completion before moving onto the next message in the queue. Therefore, no two messages (e.g., AJAX responses) will be processed in parallel.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop

Also, I've worked in JavaScript for many years and can guarantee this is how it works.

like image 80
Aaronius Avatar answered Oct 06 '22 01:10

Aaronius