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.
February 15th, 2008 at 11:46 am
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”).
March 4th, 2008 at 3:59 pm
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
March 12th, 2008 at 11:16 am
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.
April 4th, 2008 at 7:58 pm
GoTo to
Funny Action, Contacts
http://Meet-Gays.NET
April 7th, 2008 at 8:06 am
???? ???? ????? ???????????? ?????????? ??? ?????????? ??????? ???????? ???????????? ????????
http://photolive.ru
April 9th, 2008 at 4:46 am
“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
April 10th, 2008 at 5:24 pm
Hello my friends

April 15th, 2008 at 2:20 am
??????? ????? ????? + ?? ????? ???? ??????????? ?? ??????? ????? ?????? ????? (15 ?? ? ?????? ????? ???? ??????????? ????????????? ??????? *?????: ?????: ??????? ???? ?
September 30th, 2008 at 9:04 pm
“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
October 24th, 2008 at 6:55 am
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…
December 8th, 2008 at 5:20 pm
????????? ?????? ??????????? ????????? =http://spooky.nm.ru
????? ?????!!!
December 10th, 2008 at 8:17 am
> 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;
};
December 31st, 2008 at 2:52 am
Hi! Its test post from me - bromgeksinovich!
My url is bromgeksinovich.com
January 10th, 2009 at 10:11 pm
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!
January 11th, 2009 at 1:15 pm
qualitativesoft
qualitativesoft