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();
    }
}
Update 2018-01-10: Many time has past since the original post. Time has changed,  async code is every where, NodeJS is fighting the Java throne, Promises rocks, so do Futures and CompletableFuture is not yet the future but the present (or is it that maybe RXJava has put the Future into the past?). Ah, do not forget the lovely lambdas.... Cool things of Java 8 now that Java 9 is officially out in the wild !!!
Time to make our code prettier and younger:

class CalculationWindow extends JFrame {
    // ...
    public CompletableFuture calculateInSeparateThread(final URI uri) () {
        final CompletableFuture result = new CompletableFuture();
        new Thread(() -> {
              try{
          calculate(uri);Ç
          result = result + 10;
          result.complete(result);
              }catch(AnnoyingCheckedException e) {
          result.completeExceptionally(
              new RuntimeException("Not implemented"));
              }
        }
        }).start();
        return result;
    }
To be continued ...

No comments: