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 CompletableFutureTo be continued ...calculateInSeparateThread(final URI uri) () { final CompletableFuture try{ calculate(uri);Ç result = result + 10; result.complete(result); }catch(AnnoyingCheckedException e) { result.completeExceptionally( new RuntimeException("Not implemented")); } } }).start(); return result; }result = new CompletableFuture (); new Thread(() -> {