Mutant World

Tuesday, December 19, 2006

Java Closures

Java Closures seem to be the buzzword of the moment.
Unfortunately I missed the (I'm told great) JavaPolis conference in Antwerpen, Belgium, but fortunately the JavaPolis guys have put videos of the sessions online !

I recommend all people interested to watch or listen to Neal Gafter's session on closures.

The very interesting idea behind closures in Java (how they are shaped right now, at least) is the ability to write code that somehow "extends" the Java language syntax itself, adding what look like new keywords to the Java language itself.
Neal Gafter himself said that if closures where in the language before JDK 5, the new for loop syntax would probably not have been introduced.

How do closures look like ?

The proposed syntax for the closures in Java allows to write code such as:

Collection<T> elements = ...;
forEach (T element : elements) { doSomething(element); }

The forEach statement here looks like a new keyword of the Java language, but in reality is a method call (assume there is a static import such as import static java.util.Collections.forEach).

Another example is iterating over entries of a java.util.Map:

Map<K, V> props = ...
eachEntry(K key, V value : props) { doSomething(key, value); }

where again the eachEntry statement is a static method call to (for example) java.util.Collections.

One can even think of replacing the synchronized keyword with the classes from java.util.concurrent.locks:

final Lock lock = ...;
sync(lock) { oneThreadAtATime(); }

where sync is a method call, and not a keyword.
It is impressive how closures make sync look like a keyword, when compared to the real synchronized keyword.

Possibilities are endless: from automatically closing streams, to measuring elapsed time, to adding functional programming to collections, to simplify java.util.concurrent.Executor usage, etc.

Closures in Java are targeted for JDK 7. Seems strange to say, with JDK 6 released few days ago, but I cannot wait to see closures in Java.