Emerging Java Technologies at QCon

I've just finished opening the "Java Emerging Technologies" track at QCon and spent some time talking about Closures. This is a summary of what I said:

You can look at closures as blocks of code that you can pass around for execution. You can look at them as syntax sugar for inner classes. I think there is some significant power behind full closures that you miss when just looking at them from those perspectives.

This is how you define an integer 'a', in Java:

int a;

This is how you define a function 'b', in a Java Interface:

String b(int p1, int p2);

This is how you define a closure 'c', according to the BGGA proposal:

{ int, int => String } c;

This defines a closure to which you pass 2 integers and it returns a String.

Another closure 'd' takes a String and returns nothing:

{ String => } d;

We can provide an implementation of this closure:

{ String => } d = { String m =>
    System.out.println(m);
};

And then execute the closure like this:

d.invoke("Hello, World!");

The standard example (standard because it is the one used in the spec) looks like this:

public static <T,throws E extends Exception>
T withLock(Lock lock, {=>T throws E} block) throws E {
    lock.lock();
    try {
        return block.invoke();
    } finally {
        lock.unlock();
    }
}

This example can be made much easier to understand if we ignore exceptions and return types for a while:

public static void withLock(Lock lock, {=>} block) {
    lock.lock();
    try {
        block.invoke();
    } finally {
        lock.unlock();
    }
}

This is a method that takes a lock object and a closure. It then surrounds the execution of the closure with lock and unlock commands.

Normally speaking you would use this as follows:

withLock(lock, {=> System.out.println("hello"); });

However there is a special rule in the closures spec that says: If the last parameter to a method is a closure then you can write the closure outside the parameter list like this:

withLock(lock) {
    System.out.println("hello");
}

It's likely that we would not have needed the synchronized keyword if closures had been around in the beginning. It's also likely that a large amount of Java could have been defined in terms of closures. For example:

public static <throws E extends Exception>
void If(boolean condition, {=> throws E} block) throws E {
    if (condition) {
        block.invoke();
    }
}

You would use this function like this (note the capital I on If:

If (a == b) {
  System.out.println("a equals b");
}

So closures as defined by the BGGA proposal allow you to do some fairly fundamental things with the Java language.

Comments

Comments have been turned off on old posts