Bill Venners caught up with Neal Gafter at JavaPolis where they discussed Neal’s, proposal for the addition of closures to the JLS. The discussion covers many of the topics that Neal covered in his JavaPolis presentation. It also contains some insight into some of the criticisms that have been leveled at the proposal. The proposal, originally drafted by Neal, Gilad Bracha, James Gosling, and Peter von der Ahé, specifies a syntax in which one could write methods that could then be enclosed in a context (another method/class). This concept is quite different than anonymous inner classes in that it allows you to use normal Java constructs and have them behave in the expect manner. For example, a return from a method declared in anonymous inner would work quite differently than a return in a closure.
a return from a closure simply returns from the enclosing method. The fact that it's inside of a closure doesn't change the meaning of the return statement.
The discussion dives deep into how closures could be implemented. The compiler turns the closure into an interface which may appear to look like an anonymous inner class. However Neal uses a withLock( lock) {} example to demonstrate how the implementation is different than that of an anonymous inner class.
but it's not an anonymous inner class, because the scoping rules for a closure are different from an anonymous inner class's scoping rules. It creates an object that implements that interface where the body of the invoke method does what the code inside the closure says it should do. And it passes that instance as an extra parameter to the withLock method. And inside the withLock method, in order to cause that code to be executed, you have some parameter, like block—you just say block.invoke(). That's all you need to do, and it simply calls the invoke method on that interface from the object that was passed in.
The scary part of the proposal is that in order to make return work at expected, the method may have to throw an exception which would be caught in the outer scope. Given the impact that exceptions have on the runtime, one would hope that this implementation doesn’t make it. For more information on the proposal you can watch the JavaPolis presentation here. You can read the full interview here, and there are many links from Neal's blog.