12

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

Sarath
  • 9,030
  • 11
  • 51
  • 84
  • 1
    http://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649 – Ishank May 09 '13 at 08:58
  • 1
    In JavaScript, you only have a single thread so there will be no problem. – erikkallen May 09 '13 at 09:04
  • @Ishank ...thanks fr tht..but i didnt get a simple ans fr this... – Sarath May 09 '13 at 09:59
  • @erikkallen .. then wht abt this situation? – Sarath May 09 '13 at 10:00
  • 4
    there is a event queue maintained in javscript, next ajax will start when the previous is finished.. – Ishank May 09 '13 at 10:03
  • no the question is What if both calls finish exactly at the same time, same timestamp? – Sarath May 09 '13 at 10:25
  • Seems to be a duplicate of http://stackoverflow.com/questions/7863657/what-happens-if-two-process-in-different-processors-try-to-acquire-the-lock-at-e – Esailija Jul 31 '13 at 21:35
  • 1
    They won't. Even if both (somehow) finish getting delivered at the precise same moment, they will be processed sequentially. Javascript is *never* multithread (well, except for the explicit threads introduced recently, but those can't do network tasks). – Dave Aug 04 '13 at 16:01
  • i'm sorry but what exactly do you want to do ?:D – vortex Aug 05 '13 at 08:08
  • @vortex i told its a thought experiment :) – Sarath Aug 07 '13 at 09:12

2 Answers2

14

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).

Sebastien
  • 682
  • 1
  • 14
  • 26
  • 1
    This answer seems sound, however, including some verifiable and reputable references in your answer to support your claim would be excellent. – Samuel Liew Aug 04 '13 at 06:31
  • 1
    @SamuelLiew: Your comment would be excellent if you had not copied and pasted them on every answer. – kumarharsh Aug 05 '13 at 18:28
  • Apart from that, http://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649 answers the question. – kumarharsh Aug 05 '13 at 18:29
  • @Samuel: I've put a (wiki)link to the description of the OSI Model. It describes the different abstraction layers that you'll go through for every communication. You can then read about what is decided in which layer. – Sebastien Aug 06 '13 at 08:49
  • added a link to Resig's blog post about javascript timers. Do you need some other references ? – Sebastien Aug 06 '13 at 08:57
6

In Javascript asynchronous operations run in the background, but all Javascript code, including callbacks, run in the foreground thread. So it is really impossible by design that two callbacks will execute at the same time.

If the two asynchronous operations finish at the exact same time both will signal their completion at the same time, and then the Javascript scheduler will pick one of the two callbacks to run first.

Which callback goes first is implementation and operating system specific, for all intents and purposes you can assume it will be random.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152