Monday, March 28, 2011

JQTJSF: Java-quick-thread-job-splitting/forking

(Sorry about the stupid title but "laws of nature" force me to prefix anything related to Java with an annoying, uggly, empty of content and counter-intuitive acronym).

Reading about closures I found the next quite useful paragraphs (Copy&Paste from the Wikipedia):

Java allows defining "anonymous classes" inside a method; an anonymous class may refer to names in lexically enclosing classes, or read-only variables (marked as final) in the lexically enclosing method.
class CalculationWindow extends JFrame {
private volatile int result;
...
public void calculateInSeparateThread(final URI uri) {
// The expression "new Runnable() { ... }" is an anonymous class.
new Thread(
new Runnable() {
void run() {
// It can read final local variables:
calculate(uri);
// It can access private fields of the enclosing class:
result = result + 10;
}
}
).start();
}
}


Some features of full closures can be emulated by using a final reference to a mutable container, for example, a single-element array. The inner class will not be able to change the value of the container reference itself, but it will be able to change the contents of the container.

According to a Java 7 proposal[11], closures will allow the above code to be executed as:
class CalculationWindow extends JFrame {
private volatile int result;
...
public void calculateInSeparateThread(final URI uri) {
// the code #(){ /* code */ } is a closure
new Thread(#(){
calculate( uri );
result = result + 10;
}).start();
}
}

No comments: