« December 2009
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today
XML

Blog::Navigation

GetJava Download Button
Get the Source
Personal Blog

Blog::Referers

Today's Page Hits: 267

Powered by Roller Weblogger.
« E4X is not Mustang | Main | Concurrent Programmi... »
20051020 Thursday October 20, 2005

Asynchronous JavaScript with Mustang

Mustang (Java SE 6) includes JavaScript engine. How can we execute JavaScript functions asynchronously?



// This function accepts a script function and returns an object that implements
// java.util.concurrent.Callable 

function callable(func) {
        return new java.util.concurrent.Callable() {
            call: function() { return func(); }
        }
}


// create an Executor
// for 'background' executions.

var theExecutor = java.util.concurrent.Executors.newSingleThreadExecutor();

// future function executes given function asychronously
// returns a java.util.concurrent.FutureTask as result.
// calling get method on result method would potentially
// block the caller and make it wait for completion.
function future(func)  {
    return theExecutor.submit(callable(func));
}

You can save the above script code in a file (say, "future.js") and load it in jrunscript prompt and play with it. Sample jrunscript session is as follows:

js> load('future.js')
js> function f() { return 344 * 22; }
js> x = future(f)
js> x.get()

If you don't want to add a global function (future), you may do:

function callable(func) {
        return new java.util.concurrent.Callable() {
            call: function() { return func(); }
        }
}

var theExecutor = java.util.concurrent.Executors.newSingleThreadExecutor();

Function.prototype.future = function() {
    return theExecutor.submit(callable(this));
}

With above code, the caller can use the following:


function timeConsumingFunc() {
   // length computation here...
}

var result = timeConsumingFunc.future();

// when you want result value, you can say

y = result.get(); 
// the above get call would block if asynchronous computation is not completed.
// or else you will get result immediately...


Note that I've not handled function arguments for future functions. That is left as exercise to the reader :-) The JavaScript object XMLHttpRequest of AJAX fame is just a special case of running a script function asynchronously. With above scheme, you can run any script function asynchronously....



( Oct 20 2005, 06:49:19 PM IST ) Permalink del.icio.us | furl | simpy | slashdot | technorati | digg

Comments:

Post a Comment:

Comments are closed for this entry.
Copyright (C) 2005, A. Sundararajan's Weblog