Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Javascript Ajax lead to deadlocks?

I have a thought experiment. In my code I have a global variable say var changeMe; and I'm making few Ajax calls.

 //call One -- third param is the callback function
    ajaxFunction(url1, params,function(data){
        changeMe = data;
    });

//call Two
    ajaxFunction(url2, params,function(data){
        changeMe = data;
    });

So changeMe value will depend on which Ajax call finishes last, which means the call that finishes last will overwrite the value.

What if both calls finish exactly at the same time, same timestamp?

Since Javascript is single-threaded we normally won't get this problem, but this may arise in the case of setTimeout and Ajax calls. I don't know how I can replicate this issue with precision, so it still remains a thought experiment.

So how in multi-threaded conditions is a deadlock handled?

I prefer an answer like changeMe will be url1 or url2 , and a clear situation explanation..

Thanks in advance

like image 980
Sarath Avatar asked May 09 '13 08:05

Sarath


1 Answers

Javascript has an event queue. It means that it handles ALL events (user-triggered events, setTimeout events, ajax returns events) one by one, as they come.

You cannot make assumptions on the execution order, this is definitely not the right way to go. That doesn't mean that you can't do synchronization. For instance:

function processURLs() {
    var url1 = "http://www.url1.com/";
    var url2 = "http://www.url2.com/";
    var data1 = null;
    var data2 = null;

    ajaxFunction(url1, params, function(data){
        data1 = data;
        if( data2 !== null ) {
            process(data1, data2);
        }
    });

    ajaxFunction(url2, params, function(data){
        data2 = data;
        if( data1 !== null ) {
            process(data1, data2);
        } 
    });
}

You said that javascript is single-thread. That's right. That thread keeps looping and pops the events from this queue when there's events to process.

Even if the calls finished exactly at the same time and same timestamp, there will be one that will be enqueued to this event queue before the other (because your system will transmit the messages to the javascript process in some order).

If you want to know how javascript timer works with that event queue, i deeply recommend the reading of John Resig's blog post about it

If you want more information about how network events are passed to your browser (javascript), you should learn about the OSI Model.

For instance, your browser is in the OSI layer 7 (Application), but the order of network events will be decided below (layers 3 to 6).

So to sum up the answer: nobody can tell you changeMe will be url1 or url2. Javascript won't decide the order here, it will be decided in deeper layers (your network card, your operating system, etc).

like image 167
Sebastien Avatar answered Nov 06 '22 07:11

Sebastien