« October 2005 »
SunMonTueWedThuFriSat
      
1
2
3
4
8
9
10
11
12
13
15
16
17
19
22
23
27
28
30
31
     
Today
XML

Blog::Navigation

GetJava Download Button
Get the Source
Personal Blog

Blog::Referers

Today's Page Hits: 844

Powered by Roller Weblogger.
« Previous day (Oct 18, 2005) | Main | Next day (Oct 20, 2005) »
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

Copyright (C) 2005, A. Sundararajan's Weblog