« 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: 1011

Powered by Roller Weblogger.
« Previous day (Oct 19, 2005) | Main | Next day (Oct 21, 2005) »
20051021 Friday October 21, 2005

Concurrent Programming in JavaScript

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 :-)



( Oct 21 2005, 08:07:20 PM IST ) Permalink Comments [2] del.icio.us | furl | simpy | slashdot | technorati | digg

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