Java Closures

In this article, I will explain what a closure is and clear the confusion surrounding anonymous inner classes and closures, then java’s current situation with respect to closures.
First I want to emphasize the below two points:
  1. As of JDK 1.6 we don’t have closures in java.
  2. Annonymous inner classes in java are not closures.

Definition of closure

Function types and inline function-valued expression are called closures. Let me decrypt this definition for you. An anonymous function that contains some context surrounding it as a snapshot and can be passed as a parameter. This closure defintion has two parts. First one is about callback. That is, a pointer to a function that can be passed as a parameter. Second part of the definition is, this callback function will enclose some contextual information surrounding it as a snapshot and passed along with the function.
A closure is also referred to as a ‘first class object’ which can refer to attributes from its enclosing scope. As defined by Christopher Strachey in ‘Understanding Programming Languages’, a first class object can be stored in a data structure, passed as a parameter, can be returned from a function, can be constructed at runtime and independent of any identity.

In case if you are curious in Mathematics a closure is, when you operate on a members fo a set and if the resultant is always a member of that set then its called a closure.

Anonymous inner class is not closure

Anonymous classes in java are close to being called as a closure. They don’t 100% support the definition but come close to it and thats why we see lot of literature calling anonymous inner classes as closure. Why do I say its not 100%? An anonymous inner class can access “only” the final local variable of the enclosing method. It is because of this restriction, anonymous inner class in java is not a closure.
If you remember the memory management in java, you can recall that the local variables are stored in a stack. These java stacks are created when the method starts and destroyed when it returns. Unlike local variables, final fields are stored in method area which lives longer even after the return of the method. If we want to make anonymous inner class as a closure, then we should allow it to access all the fields surrounding it. But, as per the current memory management, they will be destroyed and will not be accessible after the method has returned.

Closure in Java

In that case will we get closure in java in future? We have a specification written by Peter Ahe, James Gosling, Neal Gafter and Gilad Bracha on closures for java. It gives detailed description of how a closure can be implemented in java and example code on how to use them. We have JSR 335 for closures in java named as Lambda Expressions for the Java Programming Language.

0 comments:

Post a Comment