Exploring thread synchronization in JavaScript and Rhino

Still making my way through Concurrent Programming in Java by Doug Lea.

This book is great. Yes, great. The intended audience is intermediate to advanced programmers who want a deep understanding of common problems and their solutions in concurrent, object-oriented programming. Obviously, all the examples in the book are in Java, and many details specific to the Java language and standard libraries are presented, but the text is meant to serve a greater audience looking for general concurrent programming techniques.

In the section of the book where the basics of thread synchronization are being explained, Doug provides an example class called Even that would work perfectly well in a sequential (non-multi-threaded) environment, but is likely to fail in a multi-threaded one.

As usual, I wanted try this idea out with a Java scripting language just to see if anything interesting or unexpected happens…

Although JavaScript is not a multi-threaded language/environment, the Rhino JavaScript interpreter/scripting environment allows scripting of Java in JavaScript and access to all Java types such as Thread and Runnable. Thus, you can basically compose multi-threaded JavaScript.

So here is a port of the basic idea in section 2.2 of the book to JavaScript using Rhino. The code uses a class called Even which is meant to only represent even numbers. By instantiating and instance of Even and calling its next() method, the next even number is returned. However, since the next() method is not synchronized, it is possible for multiple threads to examine the instance in an illegal state (where next() returns an odd number).


importClass(java.lang.System,
            java.lang.Thread,
            java.lang.Runnable);

/**
 *    Class for generating even numbers. Not Thread-safe!!!
 */
function Even() {
    this._n = 0;
}

/**
 *    Return the next even number. Broken Method...
 *    can return odd numbers in multi-threaded env.
 *    @returns number
 */
Even.prototype.next = function () {
    this._n++;
    this._n++;
    return this._n;
};

/**
 *    Static utility method to determine if a given
 *    number is even.
 *    @throws IllegalArgumentException if n is not
 *                      a number
 *    @param number n
 *    @returns boolean
 */
Even.isEven = function (n) {
    if ('number' != typeof n)
        throw 'IllegalArgumentException: Even.isEven only ' +
        	'accepts number args';
    return 0 == n % 2;
};

var even = new Even();

var r = new Runnable() {
    run: function () {
        while (true) {
            var x = even.next();
            if (!Even.isEven(x)) {
                throw 'RuntimeException: Thread synchronization' +
                	' is needed to ensure that instances of Even' +
                	' always return even numbers from their' +
                	' get() method';
            }
            System.out.println(Thread.currentThread().getName()+': '+x);
        }
    }
};

new Thread(r).start();
new Thread(r).start();

The problem arises in the next() method of the Even class. This method does not execute an atomic operation, but should!

At first glance, you might be tempted to make the following change to the next() method correct the problem:


Even.prototype.next = function () {
    this._n += 2;
    return this._n;
};

Unfortunately, this doesn’t work either. The += operator deceptively appears to execute an atomic operation, but it does not… it actually executes both a read and write operation. This method suffers from the same fatal flaw as the original implementation.

JavaScript (even with Rhino) does not have language-level support for synchronization like Java does through the synchronized keyword. So, at the language level, there is no fix for this broken class. However, Java 1.5 has been released with a new package of high-level concurrency utils java.util.concurrent which can be used to create the desired effect. This package was actually inspired by the package of production-ready concurrency utils provided with the Concurrent Programming book. These will run on Java 1.2.

Since I’m on Mac OS X Tiger, and have access to Java 1.5 Tiger (finally), let’s try to fix the situation using the new ReentrantLock class in java.util.concurrent.locks. Make the following change to the Event.next() instance method:



importClass(java.util.concurrent.locks.ReentrantLock);

/**
 *    Thread-safe class for generating even numbers.
 */
function Even() {
    this._n = 0;
    this.lock = new ReentrantLock();
}

/**
 *    Return the next even number.
 *    @returns number
 */
Even.prototype.next = function () {
    this.lock.lock();
    this._n++;
    this._n++;
    this.lock.unlock();
    return this._n;
};

Now the script will never break the invariants of the Even class.

15 Responses to “Exploring thread synchronization in JavaScript and Rhino”

  1. Wheenliex Says:

    Just discovered a complete list of all marked down products at Amazon, sorted by category
    and % off, ranging from 50% off to 90% off (thanks Sonja for the effort).

    Actually I never thought Amazon would have articles with 90% off, but only in the category
    Electronics there are more than 3000 of them - look for yourself, the list is on
    Bargain Hunter (which is a blog of a woman who specializes in finding good deals at
    Amazon, like Britain’s “Jeanie”).

  2. ollards Says:

    Are you ready to claim over $1500.00 in bonus software?
    It can be yours today.

    Whether you decide to stay with us or not, this software
    is yours to keep - FREE.
    No gimmicks, no strings attached. Get your access today:
    http://salazarfill.com/marketing.htm
    Very best regards,
    Aleks.
    salazarfill.com
    Riga
    Latvia

  3. pitergluzman Says:

    The Site for designer. The Big amount thematic kliparts. The References to download kliparts.
    The Catalogue of kliparts is divide into thematic sections for suitable searching for. You may download kliparts on different subjects such as nature, meal, design interior, ???????, animation kliparts, raster and vector. As well as information on pantons for designer.

  4. Beni214567 Says:

    GoTo to

    Funny Action, Contacts

    http://Meet-Gays.NET

  5. photolive Says:

    ???? ???? ????? ???????????? ?????????? ??? ?????????? ??????? ???????? ???????????? ????????
    http://photolive.ru

  6. Extelotte Says:

    “Sa,i ne conosco tawntii dibambini che possono ancora intebdere questo parlpade primijtivo, comunque ho esposto altou amcio il mio porgetto ed egli ha accettato di buon grado. Così, Rosa della Speranza, di taanot in tanto, Primo ti ingierà tramige me, uttti i compiti che odpvrai realizzare in attesa che la neve si sciolga e che tu poissa tornare a scuolq. Non è forse una bella sorpresa per te?”
    Un giodno mentre stava epttinando laa lana tosata dellew pecore pert i suoi bei feltri, scosre dalla fiunestra unh Falco gradnissimo eal vvolo inconsuetazemnte baswo, ampio e silenzios,o che si aggirava proprtio davanti alla sua casa. Rosa rimase incantata alla vista di quel meravilgiosok uccel che le volava vicinissimo e le sembrò addireittura che voleses chiamarla; poi l’dhì davvero il suo richiamo e quessta volta era rivolto veramente a lei:

    ______________
    Chat

  7. Wamembolo Says:

    Hello my friends :)
    ;)

  8. Fgv454GFR5GH Says:

    ??????? ????? ????? + ?? ????? ???? ??????????? ?? ??????? ????? ?????? ????? (15 ?? ? ?????? ????? ???? ??????????? ????????????? ??????? *?????: ?????: ??????? ???? ?

  9. misticst Says:

    “Tired of Getting Just a Few YouTube Video Views?

    “Get your Youtube video seen by thousands. Increase your youtube views
    with TUBEHITTER”

    The Biggest question you need to ask yourself “Do you want a sponsor deal with youtube?”

    There are some youtubers that make $1000’s just with the Youtube Sponsorship Program

    You dont have to be the best in making vids, all you have to have is a program that can boost your vid from 0 to 50,000 .

    Once you are on the most viewed section the 1000’s that are on youtube will spot your vid with ease.

    WITH OTHERS LOOKING AT YOUR VID YOU WILL GET 100,000 OR MORE WITHIN 24 HRS OR LESS.

    go to http://www.tubehitter.com

  10. Albert_QI Says:

    check out this new and simple web application , it lets you make your own web ID……. http://www.ziipa.com/view/StigId

    came across it yesterday and instantly became a fan of it……..
    very simple to use and there is so much you can do with it……check it out yourself , its awesome…

  11. xoxotunerccqw Says:

    ????????? ?????? ??????????? ????????? =http://spooky.nm.ru
    ????? ?????!!!

  12. prg.blogger Says:

    > Even.prototype.next = function () {
    > this.lock.lock();
    > this._n++;
    > this._n++;
    > this.lock.unlock();
    > return this._n;
    > };

    This code is still not thread-safe. The following is:

    Even.prototype.next = function () {
    this.lock.lock();
    this._n++;
    this._n++;
    var result = this._n;
    this.lock.unlock();
    return result;
    };

  13. testnikname85 Says:

    Hi! Its test post from me - bromgeksinovich!
    My url is bromgeksinovich.com

  14. gitiouttraW Says:

    Sorry about that, but we need very urgently to contact the administrator http://www.ditchnet.org. There has not been able to find the feedback. Thank you!

  15. qualitative Says:

    qualitativesoft
    qualitativesoft