AJAX, Javascript and Threading

Javascript and Microsoft's JScript are compliant with the ECMA-262 language specification.

I looked at the specification available at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf and it doesnt mention threading.

There are no keywords or intrinsic ECMAScript objects available to manage threads, or to provide for thread synchronization.

So, if threading is available in some or all browsers, the implementation is notcontrolled by this spec.

Javascript Engines

I couldnt find any details of the implementation of IE 7s Javascript engine, however, SpiderMonkey, the engine used by Firefox is documented at http://www.mozilla.org/js/spidermonkey/

The SpiderMonkey Javascript engine supports native threading!!

However, it appears that firefox only uses one JSContext for Javascript.

Without Threading, how does AJAX work?

It seems that many people blogging about AJAX mistake asynchronous requests for threading.

This is not the case. Consider the following:

I post an aysnchronous request to a web service. This request is associated with a callback function.

Since this request is asynchronous and is now being handled by the browser rather than the JavaScript engine, I can execute JavaScript code while this request is being processed by the server.

The code I choose to execute is a long running process and server will respond before the process is complete.

Does the asynchronous request and callback function execute in their own thread?

No. The callback function is not called until the long running process is complete even though the server responded quicker. Javascript queues asynchronous code when it is blocked.

Implementing our own threading model

There are libraries, written in Javascript, that imitate the programming conventions associated with threading, but these "threads" still cannot execute code concurrently.

http://www.neilmix.com/2007/02/07/threading-in-javascript-17/ uses "python style" generators introduced in Javascript 1.7

Conclusions:

  1. Microsoft need to start documenting the inner workings of their code. No more blackboxes!!!
  2. JavaScript does not support native threading.

  3. Since we cannot guarantee the order of asynchronous events, coding 'functionally' and 'immutabily' is still useful even in this single threaded environment.

    We avoid the use of global variables since asynchronous code mutating the same variable can lead to unwanted "side effects".

    We should always have a good reason to mutate!

Posted in Labels: , , |

1 comments:

  1. Anonymous Says:

    bet on sports, bet football, foootball betting
    bet online online sports betting betting online