As I've been repeatedly highlighting, Mustang (Java SE 6) includes Rhino JavaScript engine. How do we write multithreaded scripts? JavaScript engine allows Java method calls. So, we can use that to create script wrappers for Java platform classes as shown below:
// creates a java.lang.Runnable wrapping given script function.
function runnable(func) {
return new java.lang.Runnable() {
run: function() { func(); }
}
}
// add 'thread' function property to Function prototype.
Function.prototype.thread = function() {
var t = new java.lang.Thread(runnable(this));
t.start();
return t;
}
After including above code (using load function in jrunscript), we can easily create threads in script:
function myFunc() {
//... code here...
}
// start 2 threads with myFunc as starting function
myFunc.thread();
myFunc.thread();
But, what about mutual exclusion/communication/co-operation between threads? You may want locks, condition variables etc. Well, you may write few script wrappers using java.util.concurrent
API as shown below:
// creates a ReentrantLock
function lock() {
return new java.util.concurrent.locks.ReentrantLock();
}
// runs given function after acquiring given lock and releases the lock
// after the function is finished. (in effect the script function is
// 'synchronized' in Java sense
Function.prototype.sync = function(lock) {
lock.lock();
try {
this.call();
} finally {
lock.unlock();
}
}
The caller of the above code would look like:
function myFunc() {
// code here
}
// create a lock
var lk = lock();
// run myFunc in 'synchronized' way
// no two threads can run myFunc concurrently.
myFunc.sync(lk);
Note that I've not handled script functions with arguments. For eg., you may want to start a thread with a function that accepts arguments. As usual, that is left as an exercise to the reader :-)