Site Archive (Complete)
Java Blog: Should Java have Closure?
Java
SWAINE'S CAFE

Black. No Sugar. Extra Caffeine.

by Mike Swaine
ERIC BRUNO'S BLOG

Java: The Daily Grind.

by Eric Bruno
September 12, 2006

Should Java have Closure?

James Gosling recently wrote in his blog about turning his focus towards Dolphin (to be Java SE 7) and the debate around Java Closures.

You should read James Gosling's recent blog entry Block Hole Theory of Design. In particular, he talks about a language construct called closures. I must be honest; I didn’t entirely remember what a closure was when I first read the blog, but my memory was restored when I looked it up on Wikipedia.

A closure is formed when a function (or class method in the case of Java) is declared and defined entirely within another function, and the inner function accesses local variables declared within the outer function. According to Wikipedia, closures are commonly used in functional programming to defer calculation, to hide state, and as arguments to higher-order functions.

So why would you want closures in Java? First, it allows you to pass an entire function as a parameter to another function. Second, it replaces anonymous inner classes which have the restriction of requiring all local variables declared outside the inner class to be defined as final if they are to be accessed within the inner class. Without this requirement, an anonymous inner class would come close to being a closure in Java.

But a closure is really a standalone function that is represented and treated as an actual object of its own. If such an object is allowed to live on after its contained method returns, you may run into problems as the memory it attempts to access may no longer be in scope. Remember, this memory is used by local variables declared outside of the closure. Most likely this memory will need to be tracked to avoid garbage collection until the closure itself loses scope and is itself a candidate for garbage collection. It gets complicated, and there is a debate taking place now as to whether closures are worth the trouble of implementing in the Java VM.

Read this post for an excellent discussion on closures in Java. Additionally, you can take part in the closure debate (and in effect, bring closure to closure), by following the polls, blogs, and other bits information on Java.net, and some other sites:

- JDK 7 Closure Poll Results
- Java? Ruby? Both
- Getting Groovy with XML
- Closures and Java: A Tutorial

Let me know what your feelings are on closures in Java by replying to this blog entry below.

-EJB

Posted by Eric Bruno at 09:24 AM  Permalink




 
INFO-LINK


Related Sites: DotNetJunkies, SD Expo, SqlJunkies