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