Let's assume I have simple code;
var counter = 0;
var sharedResource = [];//some shared resource
function incrementAndModify(){
if(counter == 0) {
sharedResource.push(Math.random());//very sensitive data
counter++;
}
}
function init(){
incrementAndModify();
doAjaxGetWithCallback(function(){incrementAndModify();});
incrementAndModify();
}
So the question is: Will incrementAndModify() function be run atomically or not? I've read, that JS run on single thread and there can't be any concurrency issues. But the question is still open (at least for me).
instead of
doAjaxGetWithCallback(function(){incrementAndModify();});
I could write something like:
doAjaxGetWithCallback(function(){
doSomeCrazyStuffThatDoesNotUseSharedResource();
incrementAndModify();
doSomeOtherCrazyStuffThatDoesNotUseSharedResource();
});
JavaScript in the browser is single-thread (with exception to web-workers), thus you don't have to bother about concurrency. Essentially - every code block is atomic, no matter how long. If incrementAndModify()
does some very CPU-intensive time-consuming operations and AJAX response arrives, the callback will not be executed until the current incrementAndModify()
finishes and releases the only thread.
This is also the reason why synchronous AJAX calls are discouraged: AJAX request can take some time during which no other code can be executed (execution thread is unnecessarily occupied). This causes the GUI to "freeze", because no other user events are handled.
BTW this:
doAjaxGetWithCallback(function(){incrementAndModify();});
can be written like this:
doAjaxGetWithCallback(incrementAndModify);
Have no fear this will only ever alert once.
// sync example
var happened = false;
setTimeout(dontDoTwice, 0);
setTimeout(dontDoTwice, 0);
setTimeout(dontDoTwice, 0);
function dontDoTwice() {
if (!happened) {
alert("ALERT! ALERT! ALERT!");
happened = true;
}
}
Slightly more complex example: http://jsfiddle.net/7BZ6H/1/
Yep, the incrementAndModify()
function will always run atomically. That's because of the Run-to-Completion feature of javascript.
See Why no concurrency control tool in javascript for more details.