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?
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.
There are also thread-safe implementations of map() and reduce() and a public method allowing a program to temporarily lock out writers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With