<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7803021</id><updated>2011-12-17T11:09:17.121-08:00</updated><title type='text'>Neal Gafter's blog</title><subtitle type='html'>Thoughts about the future of the Java Programming Language.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gafter.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>49</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7803021.post-4819572816623842725</id><published>2010-08-26T15:18:00.001-07:00</published><updated>2010-08-26T15:38:05.522-07:00</updated><title type='text'>A couple of comments on Defender Methods</title><content type='html'>&lt;p&gt;
Brian Goetz has posted &lt;a href="http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v3.pdf"&gt;version 3 of his proposal "Defender Methods"&lt;/a&gt;, which is a way of adding methods to existing interfaces without breaking binary compatibility.  Generally speaking, I think the idea is sound but I think there are some problems with the proposal in its current form.  I would normally post my comments on the proposal to &lt;a href="http://mail.openjdk.java.net/mailman/listinfo/lambda-dev"&gt;the lambda-dev mailing list&lt;/a&gt;, which ensures that any IP embedded in my comments are formally submitted to Oracle's ownership.  However, Oracle's recent lawsuit against Google has made it clear that, even though I am a contributor to openjdk7, I do not have a license to Oracle's patents that are necessarily infringed by the use of the openjdk7 source base.  This is a very confusing position for the organizer of an open-source effort to take.  Rather than continuing to contribute IP directly to the project, I'll post my comments here and contribute them to Oracle once it is clear that I've been granted a license to the patents necessary to use openjdk7.
&lt;p&gt;
The &lt;a href="http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v3.pdf"&gt;latest version of the proposal&lt;/a&gt; has added a section on "Binary compatibility" (section 11), but that section fails to address the one binary compatibility issue raised previously: what are the binary compatibility implications of &lt;em&gt;changing&lt;/em&gt; the default for a defender method?  Since the defender method's default is an implementation detail, such a change should be binary (and source) compatible, but the resolution mechanism (section 3) makes it binary incompatible.  The proposal doesn't provide compile-time semantics for invoking an extension method or compile-time rules for when a given class declaration is legal.  At the very least there should be rules to ensure that sources that compile cleanly together do not trigger a VM error at runtime due to an ambiguous method invocation.  The most natural change of the compile-time rules to match the given runtime resolution rules would make changing the defender method's default a source incompatible change as well (because it could introduce an ambiguity).  I believe this undermines the justification for having defender methods out-of-line (section 2).  Moreover, the separation forces API designers to create vestigial public API elements (the static extension methods).
&lt;p&gt;
These issues can be addressed by (a) having defender method bodies written inline, and (b) rejecting non-abstract class declarations where some defender method does not have a unique default.
&lt;p&gt;
I suspect the proposed implementation mechanisms (sections 7 and 8) will be far too expensive compared to existing virtual method calls.  For the Interface.super calls (section 7), my suggestion is to extend the VM specification of invokespecial.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-4819572816623842725?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=4819572816623842725' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/4819572816623842725'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/4819572816623842725'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2010/08/couple-of-comments-on-defender-methods.html' title='A couple of comments on Defender Methods'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-2983558471285368877</id><published>2010-02-13T16:52:00.000-08:00</published><updated>2010-02-13T17:01:43.243-08:00</updated><title type='text'>A Syntax Option for Project Lambda (Closures for Java)</title><content type='html'>&lt;p&gt;
It was noted recently on the &lt;a
href="http://mail.openjdk.java.net/mailman/listinfo/lambda-dev"&gt;Project
Lambda mailing list&lt;/a&gt; that allowing arrays of function type would
undermine the type system.  The reason for this is a combination of
Java's covariant arrays, the natural subtypes among function types
(they are covariant on return type and contravariant on argument
types), exception checking, and the erasure implementation of
generics.  We certainly can't remove covariant arrays or checked
exceptions, and removing the subtype relationship among function types
really reduces their utility.  Unfortunately, it is almost certainly
too late to reify generics too.  Although you can't have an array of
function type, there is no problem having, for example, an &lt;tt&gt;&lt;b&gt;ArrayList&lt;/b&gt;&lt;/tt&gt;
of a function type.  So while we might prefer not to have this
restriction, it won't be much of a problem in practice.

&lt;p&gt;
There are many ways in which arrays of function type would undermine
the type system, but to give you some flavor of the problem, the
following is a method written assuming that arrays of function type
are allowed.  This method must fail in some way - either fail to
compile, or throw a &lt;tt&gt;&lt;b&gt;ClassCastException&lt;/b&gt;&lt;/tt&gt;, or an
&lt;tt&gt;&lt;b&gt;ArrayStoreException&lt;/b&gt;&lt;/tt&gt;, or something.  In all of the
implementations being considered, this method would throw
&lt;tt&gt;&lt;b&gt;IOException&lt;/b&gt;&lt;/tt&gt;, even though that isn't declared in the throws
clause of the method.  We have undermined Java's exception checking
without even a cast!

&lt;blockquote&gt;
&lt;pre&gt;&lt;b&gt;public void main(String[] args) {
    #void()[] arrayOfFunction = new #void()[1];
    Object[] objectArray = arrayOfFunction;
    objectArray[0] = #(){ throw new IOException(); };
    arrayOfFunction[0].(); // invoke the function out of the array
}
&lt;/b&gt;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;
The realization that supporting arrays of function type would
introduce a loophole in the type system makes it possible to consider
some very nice syntax options that were previously eliminated because
there was no syntactic way to write an array of function type.  But if
we disallow arrays of function type, those options can be considered.

&lt;p&gt;
My favorite of the alternatives is based on this grammar

&lt;blockquote&gt;
&lt;dl&gt;
&lt;dt&gt;&lt;em&gt;FunctionType&lt;/em&gt;:&lt;/dt&gt;
&lt;dd&gt;&lt;tt&gt;&lt;b&gt;(&lt;/b&gt;&lt;/tt&gt; &lt;em&gt;TypeList&lt;/em&gt;&lt;sub&gt;opt&lt;/sub&gt; &lt;em&gt;Throws&lt;/em&gt;&lt;sub&gt;opt&lt;/sub&gt; &lt;tt&gt;&lt;b&gt;)&lt;/b&gt;&lt;/tt&gt; &lt;tt&gt;&lt;b&gt;-&gt;&lt;/b&gt;&lt;/tt&gt; &lt;em&gt;ResultType&lt;/em&gt;&lt;/dd&gt;
&lt;dt&gt;&lt;em&gt;Expression&lt;/em&gt;:&lt;/dt&gt;
&lt;dd&gt;&lt;em&gt;LambdaExpression&lt;/em&gt;&lt;/dd&gt;
&lt;dt&gt;&lt;em&gt;LambdaExpression&lt;/em&gt;:&lt;/dt&gt;
&lt;dd&gt;&lt;tt&gt;&lt;b&gt;(&lt;/b&gt;&lt;/tt&gt; &lt;em&gt;FormalParameterList&lt;/em&gt;&lt;sub&gt;opt&lt;/sub&gt; &lt;tt&gt;&lt;b&gt;)&lt;/b&gt;&lt;/tt&gt; &lt;tt&gt;&lt;b&gt;-&gt;&lt;/b&gt;&lt;/tt&gt; &lt;em&gt;Expression&lt;/em&gt;&lt;/dd&gt;
&lt;/dl&gt;
&lt;/blockquote&gt;

&lt;p&gt;
A function type is written with the argument types between
parentheses, then a right arrow (dash greater-than), and then the
result type.

&lt;p&gt;
The most important distinction between this proposal and the existing
draft specification is that this proposal places the result type after
the argument types, instead of before.  The benefits of its simplicity
compared to the current specification are most obvious when you
combine function types and lambdas with other features.

&lt;p&gt;
Here is a simple example to show how the two proposals look.  The
example is &lt;a href="http://en.wikipedia.org/wiki/Currying"&gt;currying&lt;/a&gt;.  The
following method takes as a parameter a function of two arguments, and
returns a function of one argument that returns a function of one
argument.  Applying the resulting function to one value, and then the
result of that to another value, should have the same effect as
applying the original function to both values.  To make it
interesting, we make the argument and result types generic, and we
allow the function to throw an exception.

&lt;p&gt;
Using the &lt;a href="http://mail.openjdk.java.net/pipermail/lambda-dev/attachments/20100212/af8d2cc5/attachment-0001.txt"&gt;currently
proposed syntax for Project Lambda&lt;/a&gt;, the code would look something
like this:

&lt;pre&gt;&lt;b&gt;static &amp;lt;T,U,V,X extends Throwable&gt;
##V(U)(throws X)(T) curry(#V(T,U)(throws X) function) {
   return #(T t)(#(U u)(function.(t,u)));
}
&lt;/b&gt;&lt;/pre&gt;

&lt;p&gt;
On the other hand, with the proposal described above it looks
something like this:

&lt;pre&gt;&lt;b&gt;static &amp;lt;T,U,V,X extends Throwable&gt;
(T)-&gt;(U throws X)-&gt;V curry((T,U throws X)-&gt;V function) {
   return (T t)-&gt;(U u)-&gt;function.(t,u);
}
&lt;/b&gt;&lt;/pre&gt;

&lt;p&gt;
I've intentionally selected an example that uses the new features
heavily, so either may take a few moments of studying to understand.
But I claim the latter is much easier to follow than the former, even
once you've become familiar with the syntax.

&lt;p&gt;
You can easily write a function that yields an array as its result

&lt;pre&gt;&lt;b&gt;()-&gt;int[] arrayLambda = ()-&gt;new int[]{1, 2, 3};
&lt;/b&gt;&lt;/pre&gt;

&lt;p&gt;
With this proposed syntax there is no way to write an array of
functions.  But that is exactly what we concluded could not be made to
work within the type system anyway.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-2983558471285368877?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=2983558471285368877' title='20 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2983558471285368877'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2983558471285368877'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2010/02/syntax-option-for-project-lambda.html' title='A Syntax Option for Project Lambda (Closures for Java)'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>20</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-2322776547279444205</id><published>2009-03-10T08:16:00.000-07:00</published><updated>2009-03-10T08:23:09.307-07:00</updated><title type='text'>JDK API search in Google Toolbar</title><content type='html'>&lt;p&gt;For those of you who use the Google Toolbar, the following links will add a Java API search button to your toolbar.  I've found this to be a very handy way to locate the javadoc for the platform.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;&lt;a href="http://toolbar.google.com/buttons/add?url=http://www.javac.info/jdk_search.xml"&gt;Add Java SE 6 API search box to Google Toolbar&lt;/a&gt;&lt;/b&gt;

&lt;p&gt;&lt;b&gt;&lt;a href="http://toolbar.google.com/buttons/add?url=http://www.javac.info/openjdk_search.xml"&gt;Add OpenJDK API search box to Google Toolbar&lt;/a&gt;&lt;/b&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-2322776547279444205?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=2322776547279444205' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2322776547279444205'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2322776547279444205'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2009/03/jdk-api-search-in-google-toolbar.html' title='JDK API search in Google Toolbar'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-8467128226944848283</id><published>2009-02-13T07:34:00.000-08:00</published><updated>2009-02-13T07:39:43.635-08:00</updated><title type='text'>Language Parity: Closures and the Java VM</title><content type='html'>A &lt;a href="http://www.infoq.com/presentations/gafter-jvm-closures"&gt;video of my talk at the September 2008 JVM Language Summit&lt;/a&gt; has been posted.  It's a discussion of how Java SE is tilted toward supporting the Java language at the expense of other languages, and what we might do about it.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-8467128226944848283?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=8467128226944848283' title='12 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/8467128226944848283'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/8467128226944848283'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2009/02/language-parity-closures-and-java-vm.html' title='Language Parity: Closures and the Java VM'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>12</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-3047255195011311765</id><published>2008-08-07T23:08:00.000-07:00</published><updated>2008-08-07T23:32:03.021-07:00</updated><title type='text'>Java Closures Prototype Feature-Complete</title><content type='html'>&lt;p&gt;I'm pleased to announce that the Java Closures prototype
now supports all of the features of its specification!

&lt;p&gt;The complete source code, released under GPLv2, is in
the project's openjdk repository.
A binary build, suitable for use with an existing
JDK6, is at
&lt;a href="http://www.javac.info/closures.tar.gz"
&gt;http://www.javac.info/closures.tar.gz&lt;/a&gt;.  Other related documents
are on the website &lt;a href="http://www.javac.info/"
&gt;http://www.javac.info/&lt;/a&gt;

&lt;p&gt;Although there is room for performance tuning,
the prototype supports the full
&lt;a href="http://www.javac.info/closures-v05.html
"&gt;Closures (v0.5) specification&lt;/a&gt;.  Based on your
feedback, there are some changes in the prototype
suitable for a future update of the specification:

&lt;ul&gt;

&lt;li&gt;Renamed &lt;code&gt;Unreachable&lt;/code&gt; to &lt;code&gt;Nothing&lt;/code&gt;&lt;/li&gt;

&lt;blockquote&gt;
We adopt the name used by Scala to represent the same concept.
&lt;/blockquote&gt;

&lt;li&gt;Removed support for the type &lt;code&gt;null&lt;/code&gt;&lt;/li&gt;

&lt;blockquote&gt;
We used &lt;code&gt;null&lt;/code&gt; as a placeholder for an exception type when
none can be thrown.  The type &lt;code&gt;Nothing&lt;/code&gt; now serves that
purpose; &lt;code&gt;null&lt;/code&gt; is no longer supported as the name of a
type.

&lt;/blockquote&gt;

&lt;li&gt;Overhauled restricted versus unrestricted&lt;/li&gt;

&lt;blockquote&gt;
In the specification, an interface is considered &lt;em&gt;restricted&lt;/em&gt;
if it extends a marker interface.  Unfortunately, the specification
only provides a syntax for function type interfaces that are
unrestricted.  We modified the syntax so that a function type written
using the &lt;code&gt;=&gt;&lt;/code&gt; token designates a restricted function type,
while one written using the newly introduced &lt;code&gt;==&gt;&lt;/code&gt; token
represents an unrestricted function type.  This allows programmers to
easily write APIs that restrict (or don't restrict) the operations of
closure expressions passed as parameters.
&lt;/blockquote&gt;

&lt;li&gt;Refined restrictions&lt;/li&gt;

&lt;blockquote&gt;
We modified the distinction between restricted and unrestricted
closures.  As before, it is not legal to convert an unrestricted
closure to a restricted interface type, nor is it legal to
&lt;code&gt;break&lt;/code&gt;, &lt;code&gt;continue&lt;/code&gt;, or &lt;code&gt;return&lt;/code&gt; from
inside a restricted closure to a target outside the closure.  However,
a restricted closure is allowed to refer to a non-final local variable
from an enclosing scope.  In this case a warning is given unless one
of the following conditions holds:

&lt;ol&gt;
&lt;li&gt;The variable is not the target of any assignment, or&lt;/li&gt;
&lt;li&gt;The variable is annotated @Shared&lt;/li&gt;

&lt;/ol&gt;

&lt;p&gt;It is possible to suppress the warning by annotating some enclosing
construct &lt;code&gt;@SuppressWarnings("shared")&lt;/code&gt;.

&lt;/blockquote&gt;

&lt;li&gt;Relaxed the closure conversion&lt;/li&gt;

&lt;blockquote&gt;
In response to user feedback, we've relaxed the relationship between a
closure parameter's type and the target interface's parameter type.
Rather than requiring them to be of the same type, they are now
allowed to be related by an assignment conversion, including boxing or
unboxing.
&lt;/blockquote&gt;

&lt;li&gt;&lt;code&gt;for&lt;/code&gt;-qualified method declarations&lt;/li&gt;

&lt;blockquote&gt;
The &lt;code&gt;for&lt;/code&gt; keyword on a method declaration, meant to
introduce a control abstraction method that works like a loop, is now
treated syntactically like a modifier rather than appearing
immediately before the method name.  This helps make the declaration
site more similar to the use site.
&lt;/blockquote&gt;

&lt;li&gt;Added support for method references&lt;/li&gt;

&lt;blockquote&gt;
&lt;p&gt;We added extensive support for treating a reference to a method as
a closure using a newly introduced token &lt;code&gt;#&lt;/code&gt;.  The syntax
is borrowed from the &lt;a
href="http://docs.google.com/View?docid=ddhp95vd_6hg3qhc"&gt;FCM
proposal&lt;/a&gt;.  The semantics are as follows:&lt;/p&gt;

&lt;p&gt;A method reference written as&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre&gt;
&lt;em&gt;Primary&lt;/em&gt; # &lt;em&gt;Identifier&lt;/em&gt; ( &lt;em&gt;TypeList&lt;/em&gt; )
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;where the Primary designates an expression (as opposed to a type) is
treated the same as a closure

&lt;blockquote&gt;
&lt;pre&gt;
{ Type x0, Type x1 ... =&gt; tmp.Identifier(x0, x1 ...) }
&lt;/pre&gt;
&lt;/blockquote&gt;
or
&lt;blockquote&gt;
&lt;pre&gt;
{ Type x0, Type x1 ... =&gt; tmp.Identifier(x0, x1 ...); }
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Where tmp is a temporary value that holds the computed value of the
primary expression.  The former translation is used when the resolved
method has a non-void return type, while the latter is used when the
resolved method has a void return type.

&lt;p&gt;If the primary resolves to a type, then this is translated to

&lt;blockquote&gt;

&lt;pre&gt;
{ Type x0, Type x1 ... =&gt; Primary.Identifier(x0, x1 ...) }
&lt;/pre&gt;
&lt;/blockquote&gt;
or
&lt;blockquote&gt;
&lt;pre&gt;
{ Type x0, Type x1 ... =&gt; Primary.Identifier(x0, x1 ...); }
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;when the resolved method is static, or

&lt;blockquote&gt;
&lt;pre&gt;
{ Primary x, Type x0, Type x1 ... =&gt; x.Identifier(x0, x1 ...) }
&lt;/pre&gt;
&lt;/blockquote&gt;

or
&lt;blockquote&gt;
&lt;pre&gt;
{ Primary x, Type x0, Type x1 ... =&gt; x.Identifier(x0, x1 ...); }
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;when the resolved method is an instance method.

&lt;p&gt;In addition, optional explicit type arguments, between angle brackets,
may be placed immediately after the &lt;code&gt;#&lt;/code&gt; token.  These are
used directly in the translated method invocation to resolve the
method to be invoked.

&lt;/blockquote&gt;

&lt;li&gt;Implemented a classfile format for the &lt;code&gt;for&lt;/code&gt; qualifier&lt;/li&gt;

&lt;blockquote&gt;
We've impleemnted a class file representation of the &lt;code&gt;for&lt;/code&gt;
qualifier to support separate compilation.
&lt;/blockquote&gt;

&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-3047255195011311765?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=3047255195011311765' title='43 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3047255195011311765'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3047255195011311765'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2008/08/java-closures-prototype-feature.html' title='Java Closures Prototype Feature-Complete'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>43</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-7985322555245085577</id><published>2008-03-17T00:37:00.000-07:00</published><updated>2008-03-17T00:38:28.084-07:00</updated><title type='text'>Closures: Control Abstraction, Method References, Puzzler Solution</title><content type='html'>&lt;h1&gt;Closures: Control Abstraction, Method References, Puzzler Solution&lt;/h1&gt;
&lt;p&gt;The Java Closures prototype now supports &lt;em&gt;control abstraction&lt;/em&gt; and
implements &lt;em&gt;restricted&lt;/em&gt; closures and function types. The syntax has
changed slightly. Also, as hinted in the
&lt;a href="http://www.javac.info/consensus-closures-jsr.html"&gt;draft JSR
proposal&lt;/a&gt;, there is now support for &lt;em&gt;eta abstraction&lt;/em&gt;, which
is called &lt;em&gt;method reference&lt;/em&gt; in
&lt;a href="http://docs.google.com/View?docid=ddhp95vd_0f7mcns"&gt;Stephen
Colebourne's FCM proposal&lt;/a&gt;. We haven't updated the
&lt;a href="http://www.javac.info/"&gt;specification&lt;/a&gt;, so this will serve
as a brief tutorial on  the changes until we do. I don't know if this
will be the syntax we will end up with, but it will do for now. Finally,
we look at solutions to the closure puzzler in my previous post.&lt;/p&gt;
&lt;h3&gt;Control Abstraction&lt;/h3&gt;
&lt;p&gt;The first thing you'll notice when using the new prototype is that
the compiler gives a warning when a closure uses a local variable from an enclosing scope:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;Example.java:4: warning: [shared] captured variable i not annotated @Shared
        Runnable r = { =&amp;gt; System.out.println(i); };
                                             ^
&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;There are a few ways to make this warning go away:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;declare the variable &lt;code&gt;final&lt;/code&gt;; or&lt;/li&gt;
  &lt;li&gt;annotate the variable &lt;code&gt;@Shared&lt;/code&gt;; or&lt;/li&gt;
  &lt;li&gt;make sure the variable is not the target of any assignment expression; or&lt;/li&gt;
  &lt;li&gt;put &lt;code&gt;@SuppressWarnings(&amp;quot;shared&amp;quot;)&lt;/code&gt; on an enclosing method or class; or&lt;/li&gt;
  &lt;li&gt;use an &lt;em&gt;unrestricted&lt;/em&gt; closure, by using the &lt;code&gt;==&amp;gt;&lt;/code&gt; token
  instead of the &lt;code&gt;=&amp;gt;&lt;/code&gt; token (when possible).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;code&gt;=&amp;gt;&lt;/code&gt; token builds a &lt;em&gt;restricted&lt;/em&gt; closure that
triggers this warning. Restricted closures also do not allow a
&lt;code&gt;break&lt;/code&gt; or &lt;code&gt;continue&lt;/code&gt; statement to a target outside
the closure, nor a &lt;code&gt;return&lt;/code&gt; statement from the enclosing method.
You will rarely want to write an unrestricted closure; many (but not all) of
the things you need to do with an unrestricted closure can be expressed more
clearly with a &lt;em&gt;control invocation statement&lt;/em&gt; instead.&lt;/p&gt;
&lt;p&gt;You're not allowed to assign an unrestricted closure to a restricted
interface. A number of existing JDK interfaces, such as
&lt;code&gt;java.lang.Runnable&lt;/code&gt;, have been modified to be restricted&lt;code&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;Error: cannot assign an unrestricted closure to a restricted interface type&lt;br /&gt;        Runnable r = { ==&amp;gt; System.out.println(i); };&lt;br /&gt;                       ^&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;In the less common case that you're writing a method intended to be used as a control
API, you can write a function type with the (new) &lt;code&gt;==&amp;gt;&lt;/code&gt; token to designate
an unrestricted function (interface) type. Let's do that to write a method,
&lt;code&gt;with&lt;/code&gt;, that will automatically close a stream for us. The idea is to be able
to replace this code&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;FileInputStream input = new FileInputStream(fileName);&lt;br /&gt;try {&lt;br /&gt;    // use input&lt;br /&gt;} finally {&lt;br /&gt;    try {&lt;br /&gt;        input.close();&lt;br /&gt;    } catch (IOException ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;with this&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;with (FileInputStream input : new FileInputStream(fileName)) {
    // use input
}
&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;which is an invocation of  the following method&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;
public static void with(FileInputStream t, {FileInputStream==&amp;gt;void} block) {&lt;br /&gt;    try {&lt;br /&gt;        block.invoke(t);&lt;br /&gt;    } finally {&lt;br /&gt;        try {&lt;br /&gt;            t.close();&lt;br /&gt;        } catch (IOException ex) {&lt;br /&gt;            logger.log(Level.SEVERE, ex.getMessage(), ex);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;This is among the simplest control APIs, but it has some limitations:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;It works with the type &lt;code&gt;FileInputStream&lt;code&gt;&lt;/code&gt;&lt;/code&gt;, but not any other &lt;code&gt;Closeable&lt;/code&gt; types&lt;/li&gt;
  &lt;li&gt;It does not support &lt;a href="http://tronicek.blogspot.com/2007/12/exceptions.html"&gt;exception transparency&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;It does not support &lt;a href="http://tronicek.blogspot.com/2008/01/completion-transparency.html"&gt;completion transparency&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Completing the API by repairing these defects is left as an exercise to the reader.
A solution will be discussed in
&lt;a href="https://www28.cplan.com/cc191/session_details.jsp?isid=295579&amp;ilocation_id=191-1&amp;ilanguage=english"&gt;my
JavaOne talk &lt;em&gt;Closures Cookbook&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Method References&lt;/h3&gt;
&lt;p&gt;A natural companion to &lt;em&gt;closures&lt;/em&gt; is a way to refer to an existing method instead
of writing a closure that accepts the same arguments and just invokes the method. This is
sometimes known as &lt;a href="http://www.lambda-bound.com/book/lambdacalc/node22.html"&gt;&lt;em&gt;eta
abstraction&lt;/em&gt;&lt;/a&gt; or &lt;a href="http://docs.google.com/View?docid=ddhp95vd_6hg3qhc"&gt;&lt;em&gt;method
references&lt;/em&gt;&lt;/a&gt;. We expect closures in their final form to include support for this
convenient feature, which is why it is called out in the
&lt;a href="http://www.javac.info/consensus-closures-jsr.html"&gt;draft JSR proposal&lt;/a&gt;. The
latest version of the prototype supports this, with a syntax based on javadoc conventions.
Here are a few examples:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;{ int =&amp;gt; Integer } integerValue = Integer#valueOf(int);
{ Integer =&amp;gt; String } integerString = Integer#toString();
{ int, int =&amp;gt; int } min = Math#min(int, int);
{ String =&amp;gt; void } println = System.out#println(String);
{ =&amp;gt; String } three = new Integer(3)#toString();
{ Collection&amp;lt;String&amp;gt; =&amp;gt; String } max = Collections#max(Collection&amp;lt;String&amp;gt;);
{ =&amp;gt; Collection&amp;lt;String&amp;gt; } makeEmpty = Collections#&amp;lt;String&amp;gt;emptySet();
Runnable printEmptyLine = System.out#println();&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;Writing code as a method is sometimes more convenient than writing it as a closure:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;void doTask() {
    // a complex task to be done in the background
}


Executor ex = ...;
ex.execute(&lt;strong&gt;this#doTask()&lt;/strong&gt;);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Puzzler Solution&lt;/h3&gt;
&lt;p&gt;A couple of weeks ago we looked at
&lt;a href="http://gafter.blogspot.com/2008/02/closures-puzzler-neapolitan-ice-cream.html"&gt;a
Java puzzler involving closures&lt;/a&gt;, and a number of people discussed the underlying issue. My favorite is &lt;a href="http://www.chrononaut.org/showyourwork/?p=21"&gt;David's post &amp;quot;&lt;em&gt;Color-flavor locking breaks chiral symmetry&amp;quot;&lt;/em&gt;&lt;/a&gt;. Lessons include not exposing public fields (accessors are better) and being careful to avoid cyclic initialization dependencies.&lt;/p&gt;
&lt;p&gt;The enum language feature provides support for one solution to the puzzle: specialize each instance of the enums.&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;import java.util.*;

enum Color {
    BROWN {
        public Flavor flavor() {
            return Flavor.CHOCOLATE;
        }
    },
    RED {
        public Flavor flavor() {
            return Flavor.STRAWBERRY;
        }
    },
    WHITE {
        public Flavor flavor() {
            return Flavor.VANILLA;
        }
    };
    abstract Flavor flavor();
}

enum Flavor {
    CHOCOLATE {
        public Color color() {
            return Color.BROWN;
        }
    },
    STRAWBERRY {
        public Color color() {
            return Color.RED;
        }
    },
    VANILLA {
        public Color color() {
            return Color.WHITE;
        }
    };
    abstract Color color();

}

class Neapolitan {

    static &amp;lt;T,U&amp;gt; List&amp;lt;U&amp;gt; map(List&amp;lt;T&amp;gt; list, {T=&amp;gt;U} transform) {
        List&amp;lt;U&amp;gt; result = new ArrayList&amp;lt;U&amp;gt;(list.size());
        for (T t : list) {
            result.add(transform.invoke(t));
        }
        return result;
    }

    public static void main(String[] args) {
        List&amp;lt;Color&amp;gt; colors = map(Arrays.asList(Flavor.values()), { Flavor f =&amp;gt; f.color() });
        System.out.println(colors.equals(Arrays.asList(Color.values())));

        List&amp;lt;Flavor&amp;gt; flavors = map(Arrays.asList(Color.values()), { Color c =&amp;gt; c.flavor() });
        System.out.println(flavors.equals(Arrays.asList(Flavor.values())));
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;Another elegant solution, due to 5er_levart, uses closures:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;enum Color {
    BROWN({=&gt;Flavor.CHOCOLATE}),
    RED({=&gt;Flavor.STRAWBERRY}),
    WHITE({=&gt;Flavor.VANILLA});

    private final {=&gt;Flavor} flavor;

    public Flavor flavor() { return flavor.invoke(); }

    Color({=&gt;Flavor} flavor) {
        this.flavor = flavor;
    }
}

enum Flavor {
    CHOCOLATE({=&gt;Color.BROWN}),
    STRAWBERRY({=&gt;Color.RED}),
    VANILLA({=&gt;Color.WHITE});

    private final {=&gt;Color} color;

    public Color color() { return color.invoke(); }

    Flavor({=&gt;Color} color) {
        this.color = color;
    }
}
&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;In both solutions the idea is to compute the value lazily, a key technique to break dependency cycles.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-7985322555245085577?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=7985322555245085577' title='23 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/7985322555245085577'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/7985322555245085577'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2008/03/closures-control-abstraction-method.html' title='Closures: Control Abstraction, Method References, Puzzler Solution'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>23</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-8792241959435745973</id><published>2008-02-05T09:21:00.000-08:00</published><updated>2008-02-05T09:23:12.532-08:00</updated><title type='text'>Closures Puzzler: Neapolitan Ice Cream</title><content type='html'>&lt;p&gt;
    People experience the world in different ways, using different
    senses. Some people view the world primarily through sight. Do you
    see what I mean? Some through sound. Do you hear me? Some
    experience the world only after thought and reflection. Do you
    know what I mean?  Some point out "smells" in code as a way of
    criticizing its design.
    This puzzle explores the question of whether people experiencing
    the same thing through different senses are really experiencing
    the same thing at all.  What is the program's output, and why?
    &lt;/p&gt;

    &lt;p&gt;
    This puzzle uses &lt;a href="http://www.javac.info/"&gt;Java
    Closures&lt;/a&gt;, so if you want to try it you should download the
    prototype &lt;a
    href="http://www.javac.info/closures.tar.gz"&gt;here&lt;/a&gt;.  You can
    download the puzzle sources &lt;a
    href="http://www.javac.info/Neapolitan.java"&gt;here&lt;/a&gt;.  Comments
    on this blog post will not be posted to avoid spoiling the puzzle.
    &lt;/p&gt;

&lt;blockquote&gt;
&lt;pre&gt;
import java.util.*;

enum Color {
    BROWN(Flavor.CHOCOLATE),
    RED(Flavor.STRAWBERRY),
    WHITE(Flavor.VANILLA);
    final Flavor flavor;
    Color(Flavor flavor) {
        this.flavor = flavor;
    }
}

enum Flavor {
    CHOCOLATE(Color.BROWN),
    STRAWBERRY(Color.RED),
    VANILLA(Color.WHITE);
    final Color color;
    Flavor(Color color) {
        this.color = color;
    }
}

class Neapolitan {

    static &amp;lt;T,U&gt; List&amp;lt;U&gt; map(List&amp;lt;T&gt; list, {T=&gt;U} transform) {
        List&amp;lt;U&gt; result = new ArrayList&amp;lt;U&gt;(list.size());
        for (T t : list) {
            result.add(transform.invoke(t));
        }
        return result;
    }

    public static void main(String[] args) {
        List&amp;lt;Color&gt; colors = map(Arrays.asList(Flavor.values()), { Flavor f =&gt; f.color });
        System.out.println(colors.equals(Arrays.asList(Color.values())));

        List&amp;lt;Flavor&gt; flavors = map(Arrays.asList(Color.values()), { Color c =&gt; c.flavor });
        System.out.println(flavors.equals(Arrays.asList(Flavor.values())));
    }
}
&lt;/pre&gt;
&lt;/blockquote&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-8792241959435745973?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=8792241959435745973' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/8792241959435745973'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/8792241959435745973'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2008/02/closures-puzzler-neapolitan-ice-cream.html' title='Closures Puzzler: Neapolitan Ice Cream'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-4922325604477316744</id><published>2008-01-11T17:16:00.001-08:00</published><updated>2008-01-12T11:22:53.267-08:00</updated><title type='text'>Is the Java Language Dying?</title><content type='html'>&lt;p&gt;We tend to think of programming languages in two categories:
&amp;quot;living languages&amp;quot; in which we should seriously consider
developing new code, and &amp;quot;legacy languages&amp;quot; that we mainly
use, if at all, because we have to maintain an existing code base. The
act of classifying a language into one or the other category helps us
decide what, if anything, we might consider doing to change the
language. If a language is primarily a legacy language, changes should
be aimed at making it easier to maintain and modify existing bodies of
code. A living language, on the other hand, also benefits from changes
that make it easier to design, develop, and maintain new code. Living
languages evolve to reduce &lt;i&gt;accidental complexity&lt;/i&gt;.


&lt;blockquote&gt;&amp;quot;What does a high-level language accomplish? It frees a
program from much of its accidental complexity. An abstract program
consists of conceptual constructs: operations, datatypes, sequences,
and communication. The concrete machine program is concerned with bits,
registers, conditions, branches, channels, disks, and such. To the
extent that the high-level language embodies the constructs wanted in
the abstract program and avoids all lower ones, it eliminates a whole
level of complexity that was never inherent in the program at all.&amp;quot;
-&lt;em&gt;&lt;a href="http://info.computer.org/portal/site/computer/menuitem.eb7d70008ce52e4b0ef1bd108bcd45f3/index.jsp?&amp;amp;path=computer/homepage/misc/Brooks&amp;amp;file=index.xml&amp;amp;xsl=article.xsl&amp;amp;"&gt;No Silver Bullet - Fred Brooks&lt;/a&gt; &lt;/em&gt;
&lt;/blockquote&gt;


&lt;p&gt;Programs written in legacy languages tend to exhibit a high degree
of accidental complexity

&lt;a
href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html"&gt;[&lt;i&gt;Code's
Worst Enemy&lt;/i&gt;, Steve Yegge]&lt;/a&gt;

&lt;a
href="http://bc-squared.blogspot.com/2007/12/mr-yegge-meets-mr-brooks.html"&gt;[&lt;i&gt;Mr. Yegge
meets Mr. Brooks&lt;/i&gt;, Brian C Cunningham]&lt;/a&gt;.

Early in the life of a
language, the complexity of programs written in that language may
appear to be essential, but as we learn more about software
engineering and programming languages, we find patterns of complexity
appearing in the code that can be eliminated by improved languages.


&lt;p&gt;A good example of this is garbage collection. In C and C++, memory
management is a pervasive concern. Smart pointers and destructors
help, but they do not significantly reduce the complexity of memory
management. In languages with garbage collection, most of the
complexity of memory management is assumed by the implementation of
the language. Most languages that have been introduced in the past ten
years support garbage collection.

&lt;p&gt;Another example is concurrency. The
threads-and-locks-and-semaphores primitives of Java enable
parallel programming, but require that programmers express concurrency
at a fairly low level. This has been &amp;quot;good enough&amp;quot; for some
time, as most programs are not deployed on highly concurrent
hardware. But that is changing

[&lt;a href="http://www.gotw.ca/publications/concurrency-ddj.htm"&gt;&lt;i&gt;The Free Lunch Is Over&lt;/i&gt;, Herb Sutter]&lt;/a&gt;.

Libraries such as &lt;a
href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html"&gt;java.util.concurrent&lt;/a&gt;
and &lt;a
href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166ydocs/"&gt;Doug Lea's
fork-join framework&lt;/a&gt; help somewhat, but in many cases they
introduce complexities of their own. Other languages that support
closures, such as &lt;a href="http://www.scala-lang.org/"&gt;Scala&lt;/a&gt; make
fork-join-like libraries much easier to use. Scala supports &lt;a
href="http://portal.acm.org/citation.cfm?id=177584&amp;amp;dl=GUIDE&amp;amp;coll=GUIDE&amp;amp;CFID=10370783&amp;amp;CFTOKEN=82858580"&gt;&lt;i&gt;control
abstraction&lt;/i&gt; [Crowl and LeBlanc]&lt;/a&gt;,

which allows the &lt;a
href="http://debasishg.blogspot.com/2006/11/threadless-concurrency-on-jvm-aka-scala.html"&gt;libraries
to manage much of the complexity associated with concurrency [Debasish Ghosh]&lt;/a&gt;.


&lt;a
href="http://lampwww.epfl.ch/%7Eodersky/papers/jmlc06.pdf"&gt;Support&lt;/a&gt;
for the &lt;a
href="http://lamp.epfl.ch/%7Ephaller/doc/haller07coord.pdf"&gt;Actors
model [Haller and Odersky]&lt;/a&gt;, for example, can be expressed cleanly as &lt;a
href="http://lamp.epfl.ch/%7Ephaller/actors.html"&gt;a library in
Scala&lt;/a&gt;

&lt;p&gt;Besides &lt;a
href="http://portal.acm.org/citation.cfm?id=177584&amp;amp;dl=GUIDE&amp;amp;coll=GUIDE&amp;amp;CFID=10370783&amp;amp;CFTOKEN=82858580"&gt;raising
the level of abstraction of concurrent code&lt;/a&gt;, control abstraction
also raises the level of abstraction for sequential code by &lt;a
href="http://www.parleys.com/display/PARLEYS/An+update+on+Java+Closures"&gt;eliminating
whole categories of boilerplate, which can instead be moved into
common library code&lt;/a&gt;.  This kind of boilerplate cannot be
significantly reduced by adding one or two custom statements to the
language, because such built-in forms necessarily make assumptions
about the use cases that narrow their applicability. For example, &lt;a
href="http://docs.google.com/View?docid=dffxznxr_1nmsqkz"&gt;ARM
blocks&lt;/a&gt; don&amp;#39;t document how they handle exceptions arising from
the close() method. One example in the proposal suggests they are
silently swallowed at runtime, which may work for many cases involving
I/O streams, but another example given is a transactional API, in
which ignoring such exceptions is precisely wrong.  Without a
specification for the syntax and semantics, the reader is welcome to
imagine the most favorable treatment of each use case. But &lt;a
href="http://markmahieu.blogspot.com/2008/01/cicearm-observations.html"&gt;an
attempt to reconcile these and other conflicting requirements may show
the approach cannot be salvaged&lt;/a&gt;. Perhaps that is why no progress
has been made since mid 2006.


&lt;p&gt;What about Java? Is it a living language, or &lt;a
href="http://www.infoworld.com/article/07/12/28/52FE-underreported-java_1.html"&gt;a
legacy language like Cobol&lt;/a&gt;?  This question underlies much of the
debate about how to move the Java programming language forward, if at
all. Carl Quinn asked at the December 14, 2007, JavaPolis Future of
Computing Panel (to be published on &lt;a href="http://www.parleys.com/"&gt;
http://www.parleys.com&lt;/a&gt;): &amp;quot;How can we address the issue of
evolving the [Java] platform, language, and libraries without breaking
things?&amp;quot;

&lt;blockquote&gt;
Neal Gafter:
&amp;quot;If you don&amp;#39;t want to change the meaning of anything ever,
you have no choice but to not do anything.  The trick is to minimize
the effect of the changes while enabling as much as possible.  I think
there&amp;#39;s still a lot of room for adding functionality without
breaking existing stuff...&amp;quot;
&lt;/blockquote&gt;

&lt;blockquote&gt;
Josh Bloch: &amp;quot;My view of what really happens is a little bit
morbid. I think that languages and platforms age by getting larger and
clunkier until they fall over of their own weight and die very very
slowly, like over ... well, they&amp;#39;re all still alive (though not
many are programming Cobol anymore).  I think it&amp;#39;s a great thing,
I really love it.  I think it&amp;#39;s marvelous.  It&amp;#39;s the cycle of
birth, and growth, and death. I remember James saying to me [...]
eight years ago &amp;#39;It&amp;#39;s really great when you get to hit the
reset button every once and a while.&amp;#39;&amp;quot; &lt;/blockquote&gt;

&lt;p&gt;Josh may well be right. If so, we should place Java on life support
and move our development to new languages such as Scala. The fork-join
framework itself is an example of &lt;a
href="http://en.wikipedia.org/wiki/Higher-order_function"&gt;higher-order
functional programming&lt;/a&gt;, which &lt;a
href="http://www.parleys.com/display/PARLEYS/The+Closures+Controversy"&gt;Josh
argues&lt;/a&gt; is a style that &lt;a
href="http://gafter.blogspot.com/2007/12/what-flavor-of-closures.html#c8863950537789037629"&gt;we
should neither encourage nor support in Java&lt;/a&gt;. Is it really time to
move on?


&lt;p&gt;Personally, I believe rumors of Java&amp;#39;s demise are greatly
exaggerated. We should think of Java as a living language, and strive
to eliminate much of the accidental complexity of Java programs. I
believe it is worth adding support for closures and control
abstraction, to reduce such complexity of both the sequential and
concurrent aspects of our programs. At the same time, for completely
new code bases, we should also consider (and continue to develop)
newer languages such as Scala, which benefit from the lessons of Java.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-4922325604477316744?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=4922325604477316744' title='41 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/4922325604477316744'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/4922325604477316744'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2008/01/is-java-dying.html' title='Is the Java Language Dying?'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>41</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-9093673420279741337</id><published>2007-12-13T07:48:00.000-08:00</published><updated>2009-06-30T10:46:44.311-07:00</updated><title type='text'>What flavor of closures?</title><content type='html'>&lt;p&gt;
I just attended Josh
Bloch's presentation at JavaPolis, where he asks
the community whether they want Java to support function types, or if
they'd prefer that people write these things the way they do today.
His examples are carefully selected from the most twisted of the test
suite.  Compiler test suites are a good place to find the most twisted
but unrealistic uses of any given language feature.  I thought it
would be interesting to look at the question in the context of a real
API.  You probably know my opinion, but just to be clear, here is &lt;a
href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166ydocs/jsr166y/forkjoin/ParallelArray.html#combine(js\
r166y.forkjoin.ParallelArray,%20jsr166y.forkjoin.Ops.Combiner)"&gt;
an excerpt from Doug Lea's fork-join framework&lt;/a&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre&gt;
/**
 * An object with a function accepting pairs of objects, one of
 * type T and one of type U, returning those of type V
 */
interface Combiner&amp;lt;T,U,V&amp;gt; {
  V combine(T t, U u);
}
class ParallelArray&amp;lt;T&gt; {
  /**
   * Returns a ParallelArray containing results of applying
   * combine(thisElement, otherElement) for each element.
   */
  &amp;lt;U,V&gt; ParallelArray&amp;lt;V&gt; combine(
    ParallelArray&amp;lt;U&gt; other,
    Combiner&amp;lt;? super T, ? super U, ? extends V&gt; combiner) { ... }
}
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;
And &lt;a
href="http://www.javac.info/jsr166z/jsr166z/forkjoin/ParallelArray.html#combine(jsr166z.forkjoin.Paralle\
lArray,%20info.javac.function.OOO)"&gt;the
equivalent code ported to use the features of the closures spec&lt;/a&gt;:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre&gt;
class ParallelArray&amp;lt;T&gt; {
  /**
   * Returns a ParallelArray containing results of applying
   * combine(thisElement, otherElement) for each element.
   */
  &amp;lt;U,V&gt; ParallelArray&amp;lt;V&gt; combine(
    ParallelArray&amp;lt;U&gt; other,
    { T, U =&gt; V } combiner) { ... }
}
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The question Josh asks is this: which version of this API would you
prefer see?
&lt;/p&gt;

&lt;p&gt;
The point he makes is that function types enable (he says "encourage")
an "exotic" style of programming - functional programming - which
should be discouraged, otherwise the entire platform will become
infected with unreadable code.  Although functional programming is
just as possible with or without function types - they are just
shorthand for interface types, after all - Josh prefers the language
provide syntactic vinegar for these techniques.
&lt;/p&gt;

&lt;p&gt;
Part of his talk was about the problems of being able to use nonlocal
return by default in a closure.  See my previous blog post for a
description of how this theoretical problem won't exist in the next
version of the spec, and doesn't exist in the prototype today.
&lt;/p&gt;

&lt;p&gt;
Finally, Josh showed that if you want to use something like eachEntry
to loop over a map, and you want to be able to use primitive types for
the loop variables, autoboxing doesn't work and you'd have to define
81 different versions of the eachEntry method (one for each possible
primitive type in each position).  That's true, just as it's true that
you'd have to define 81 different versions of the Map API if you want
to be able to handle primitives in them.  If it turns out to be a good
idea to make autoboxing work for the incoming arguments to a closure,
that is a small tweak to the closure conversion.  These kinds of
issues can be addressed in a JSR.
&lt;/p&gt;

&lt;p&gt;
&lt;a href="http://www.parleys.com/display/PARLEYS/Home#title=The%20Closures%20Controversy;slide=17;talk=5210267"&gt;Josh's
vision for an alternative&lt;/a&gt; is &lt;a
href="http://docs.google.com/View?docid=k73_1ggr36h"&gt;Concise Instance
Creation Expressions&lt;/a&gt; along with adding &lt;a
href="http://docs.google.com/View?docid=dffxznxr_1nmsqkz"&gt;a moderate number
of new statement forms&lt;/a&gt;.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-9093673420279741337?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=9093673420279741337' title='45 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/9093673420279741337'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/9093673420279741337'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/12/what-flavor-of-closures.html' title='What flavor of closures?'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>45</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-1029343707871820250</id><published>2007-12-03T23:16:00.000-08:00</published><updated>2007-12-05T07:57:34.862-08:00</updated><title type='text'>Restricted Closures</title><content type='html'>&lt;blockquote&gt;
&lt;p&gt;
&lt;em&gt;Note: this discusses a feature of the Closures specification that was published back in February, but which is likely to change in an upcoming revision.&lt;/em&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
The &lt;a href="http://www.javac.info/"&gt;Closures for Java
specification&lt;/a&gt;, version 0.5, contains a special marker interface
&lt;code&gt;java.lang.RestrictedFunction&lt;/code&gt;.  When a closure is converted
to an interface that extends &lt;code&gt;RestrictedFunction&lt;/code&gt;, this
prevents the closure from doing certain operations.  Specifically, it
prevents accessing mutated local variables from an enclosing scope, or
using a &lt;code&gt;break&lt;/code&gt;, &lt;code&gt;continue&lt;/code&gt;, or
&lt;code&gt;return&lt;/code&gt; to a target outside the closure.  The idea is that
APIs that are intended to be used in a concurrent setting would want
to receive restricted rather than unrestricted closures to prevent
programmers from shooting themselves in the foot.
&lt;/p&gt;

&lt;p&gt;
Two weeks ago &lt;a href="http://markmahieu.blogspot.com/"&gt;Mark
Mahieu&lt;/a&gt; contacted me regarding his experience with the &lt;a
href="http://gafter.blogspot.com/2007/11/closures-prototype-update-and-extension.html"&gt;closures
version of the fork-join framework&lt;/a&gt;.  Because I had ported that API
before I had implemented any of the operations that would be
restricted, and before &lt;code&gt;RestrictedFunction&lt;/code&gt; itself, I had
simply not provided any restrictions at all.  Mark was wondering how
to do it:

&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
I hadn't looked at the &lt;a
href="http://www.javac.info/jsr166z/jsr166z/forkjoin/package-summary.html"&gt;jsr166y
javadoc&lt;/a&gt; before you &lt;a
href="http://gafter.blogspot.com/2007/10/java-closures-first-prototype.html"&gt;linked
to it on your blog&lt;/a&gt;, so I had the chance to compare the two
versions on equal terms, and I can honestly say that I found the
closures version of the API to be much more approachable at first
blush.  I also suspect that the majority of the Java programmers I
work with would feel the same way, once comfortable with function type
syntax.
&lt;/p&gt;

&lt;p&gt;One thing I did wonder was whether a method like
&lt;code&gt;ParallelArray.combine()&lt;/code&gt; could be declared as:
&lt;p&gt;

&lt;blockquote&gt;
&lt;pre&gt;public &amp;lt;U,V,C extends {T,U=&gt;V} &amp;amp; RestrictedFunction&gt; ParallelArray&amp;lt;V&gt; combine(ParallelArray&amp;lt;U&gt; other, C combiner) { ... }
&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;
but my reading of the specification suggests that the type C won't be
a valid target for closure conversion.  Maybe I'm being greedy, but in
certain cases (jsr166y being a good example) I'd ideally want both the
clarity provided by using function types in place of a multitude of
interfaces, and the compile-time checking afforded by
&lt;code&gt;RestrictedFunction&lt;/code&gt;.  Having said that, I think the
additional type parameter above negates those gains in clarity
somewhat, even if it were an option.
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
I responded, describing what I had been planning to do in the next
minor update of the spec:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
I expect to make that work. However, I hope it won't be necessary. I
expect to support function types like
&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre&gt;{T,U=&gt;V}&amp;amp;RestrictedFunction
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;

directly. For example
&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre&gt;public &amp;lt;U,V&gt; ParallelArray&amp;lt;V&gt; combine(ParallelArray&amp;lt;U&gt; other, {T,U=&gt;V}&amp;amp;RestrictedFunction combiner) { ... }
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;
You will be allowed to intersect a function type with non-generic
marker interfaces such as &lt;code&gt;RestrictedFunction&lt;/code&gt;,
&lt;code&gt;Serializable&lt;/code&gt;, etc. Unfortunately, I will have to rev the
spec to support this.

&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;
Since that time I've been discussing this issue with a number of
people. Some, who believe that the concurrent use cases are primary,
or who believe that "Mort" programmers will blithely copy-and-paste
code from anonymous inner classes (which have different semantics)
into closures, suggest that the default is backwards: closures and
function types should be &lt;em&gt;restricted&lt;/em&gt; unless specific action is
taken to make them otherwise.  Reversing the sense of the marker
interface doesn't work (it violates subtype substitutability), but
there may be other ways to accomplish it.
On the other hand, there
are others who believe the synchronous use cases, such as control
APIs, are primary (even when used in a concurrent setting), and prefer
not to see the language cluttered with support for the restictions at
all.  Instead, they would prefer that any such restrictions take the
form of warnings (which the programmer might suppress or ask javac to
escalate to errors).  I have sympathy for both camps.
&lt;/p&gt;

&lt;p&gt;
Another possibility would be to produce a warning whenever you use a
nonlocal transfer at all and do away with
&lt;code&gt;RestrictedFunction&lt;/code&gt;. The way to suppress the warning would
be with a &lt;code&gt;@SuppressWarning("nonlocal-transfer")&lt;/code&gt;
annotation. Could we make it an error instead of a warning? This may
make the interface easier to read, but it doesn't give the API
designer any way to express a preference. It may make control APIs
painful to use.

&lt;/p&gt;

&lt;p&gt;
Finally, it would be possible to use a different syntax for restricted
and unrestricted function types and closures. For example, one using
the =&gt; token would be restricted, not allowing nonlocal transfers.
One using a different token such as ==&gt; or #&gt; would be unrestricted,
allowing nonlocal transfers. The idea is that if you want an
unrestricted closure, you'd have to use the slightly more awkward
syntax, and the receiving type must also be of the unrestricted
variety.  The control invocation syntax would be defined in terms of
the unrestricted form.  This enables API designers to express a
preference for whether or not clients would be allowed to write
unrestricted closures (and therefore, whether or not they would be
allowed to use the control invocation syntax).
&lt;/p&gt;
&lt;p&gt;
This can be made to work using only concepts already in the spec.  The
unrestricted form of a function type would be defined as an interface
type as in the current spec. The restricted form would be the same but
with &lt;code&gt;RestrictedFunction&lt;/code&gt; mixed in. With this approach there
is no need for the explicit "&amp;amp;" conjunction-type syntax for
function types.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-1029343707871820250?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=1029343707871820250' title='27 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/1029343707871820250'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/1029343707871820250'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/12/restricted-closures.html' title='Restricted Closures'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>27</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-2943144519087363192</id><published>2007-11-20T19:20:00.000-08:00</published><updated>2007-11-20T19:22:11.690-08:00</updated><title type='text'>Closures Prototype Update and Extension Methods</title><content type='html'>&lt;h3&gt;Closures Prototype Update&lt;/h3&gt;

&lt;p&gt;
The &lt;a href="http://www.javac.info/"&gt;Closures for Java&lt;/a&gt; prototype
now allows a closure to access mutated local variables from an
enclosing scope.  You can download &lt;a
href="http://www.javac.info/closures.ztar"&gt;the prototype here&lt;/a&gt;.
You can also download &lt;a href="http://www.javac.info/jsr166z.ztar"&gt;the
sources for the rewritten parts of Doug Lea's fork-join library,
ported to use function types.&lt;/a&gt; It is a good example of how APIs can
be affected by these language changes.  Personally, I find the API
simplifications to be quite compelling.  If you're on the fence about
function types, I recommend you have a look.  Any feedback you may
have is most welcome!
&lt;/p&gt;

&lt;p&gt;
I mentioned previously that I'm working on a number of smaller
language features, which hopefully will be considered for JDK7. For
now, I'd like to talk about just one of them.
&lt;/p&gt;

&lt;h3&gt;Extension Methods&lt;/h3&gt;

&lt;p&gt;
Once an API has been published, you can't add methods to it without
breaking backward compatibility. That's because implementations of the
old version of the interface don't provide an implementation of any
new methods.  You can use abstract classes instead of interfaces, and
only add concrete methods in the future. Unfortunately, that limits
you to single inheritance.
&lt;/p&gt;

&lt;p&gt;
One way API designers work around this limitation is to add new
functionality to an interface by writing static utility functions. For
example, &lt;code&gt;java.util.Collection.sort&lt;/code&gt; acts as an extension
of &lt;code&gt;java.util.List&lt;/code&gt;. But such methods are less convenient
to use, and code written using them is more difficult to read.
&lt;/p&gt;

&lt;p&gt;
Extension methods enable programmers to provide additional methods
that clients of an interface can elect use as if they are members of
the interface.  Todd Millstain's &lt;a
href="http://www.cs.ucla.edu/~todd/research/expanders/"&gt;&lt;em&gt;Expanders&lt;/em&gt;&lt;/a&gt;
are the most full-featured version of this feature.
The simplest version of this feature that I advocate would be to
enable statically-imported methods to be used as if members of their
first argument type.  For example:
&lt;/p&gt;

&lt;code&gt;
&lt;pre&gt;    import static java.util.Collections.sort;
    ...
    List&amp;lt;String&amp;gt; list = ...;
    list.sort();&lt;/pre&gt;
&lt;/code&gt;

&lt;p&gt;
Extension methods are completely orthogonal to closures, but they
enable a number of typical functional-style programming patterns to be
expressed more directly in Java using extension methods that accept
closures.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-2943144519087363192?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=2943144519087363192' title='32 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2943144519087363192'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2943144519087363192'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/11/closures-prototype-update-and-extension.html' title='Closures Prototype Update and Extension Methods'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>32</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-2695159945883317339</id><published>2007-10-28T17:05:00.000-07:00</published><updated>2007-10-28T17:11:18.297-07:00</updated><title type='text'>Java Closures: first prototype</title><content type='html'>&lt;p&gt;
I've finally had some time to make progress on a prototype of
closures. If you want to see what an API looks like, you can compare
&lt;a
href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166ydocs/jsr166y/forkjoin/package-summary.html"&gt;
Doug Lea's jsr166y fork-join framework&lt;/a&gt; to &lt;A
href="http://www.javac.info/jsr166z/jsr166z/forkjoin/package-summary.html"&gt;the
same API ported to use the language features of the prototype&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
If you want to try it, you can &lt;A
href="http://www.javac.info/closures.ztar"&gt;download an executable
version of the prototype here&lt;/a&gt;.  Make sure a JDK6 version of java
and javac are on your path.  This is binary-licensed under the JRL,
but if a JSR is created I expect to license it under GPLv2.  There are
a few small test cases included.
&lt;/p&gt;

&lt;p&gt;
This prototype supports
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;&lt;a href="http://www.javac.info"&gt;the BGGA function type&lt;/a&gt; syntax&lt;/li&gt;
    &lt;li&gt;closure literals&lt;/li&gt;
    &lt;li&gt;the closure conversion&lt;/li&gt;
    &lt;li&gt;the null type, disjunctive types, and exception transparency&lt;/li&gt;
    &lt;li&gt;definite assignment&lt;/li&gt;
    &lt;li&gt;Unreachable and completion transparency.&lt;/li&gt;
    &lt;li&gt;Catching multiple exceptions at once like  catch(X1|X2 ex) { ...&lt;br&gt;
      [not closely related to closures but the implementation was simple once closures are there]&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
This prototype does not yet support
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;a closure using a mutated variable from the enclosing scope&lt;/li&gt;
    &lt;li&gt;nonlocal control-flow (break, return, and continue)&lt;/li&gt;
    &lt;li&gt;the control invocation statement and loop abstractions &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
I'm intentionally distributing it before these features are
available. The idea is that people can try this version, and compare
it to the next version with these features working.
&lt;/p&gt;

&lt;p&gt;
Separately, I'm working on a set of smaller language extensions for
JDK7, some of which interact very nicely with Closures.  For example,
"extension methods" enable you to have the effect of adding methods to
existing interfaces (e.g. adding "each", "filter", etc to Collection)
without breaking backward compatibility.  I'll write more about these
over the next few days.
&lt;/p&gt;

&lt;p&gt;
This is still rough around the edges, but any feedback you have is
most welcome.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-2695159945883317339?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=2695159945883317339' title='83 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2695159945883317339'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2695159945883317339'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/10/java-closures-first-prototype.html' title='Java Closures: first prototype'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>83</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-6084980739329511130</id><published>2007-07-31T00:27:00.000-07:00</published><updated>2007-07-31T01:00:18.840-07:00</updated><title type='text'>Internal Versus External Iterators</title><content type='html'>&lt;p&gt;In &lt;a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FDesign-Patterns-Object-Oriented-Addison-Wesley-Professional%2Fdp%2F0201633612&amp;tag=wwwgaftercom-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325"&gt;
            the "Gang Of Four" Patterns book&lt;/a&gt;'s&lt;img src="http://www.assoc-amazon.com/e/ir?t=wwwgaftercom-20&amp;amp;l=ur2&amp;amp;o=1" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
        discussion of the Iterator pattern, we read (page 260):&lt;/p&gt;
        &lt;blockquote&gt;
            &lt;p&gt;
                Who controls the iteration? A fundamental issue is deciding which party controls the iteration, the 
                iterator or the client that uses the iterator. When the client controls the iteration, the iterator is called an 
                &lt;i&gt;external iterator&lt;/i&gt; (C++ and Java), and when the iterator controls it, the iterator is an &lt;i&gt;internal iterator&lt;/i&gt; 
                (Lisp and functional languages).  Clients that use an external iterator must advance the traversal and 
                request the next element explicitly from the iterator. In contrast, the client hands an internal iterator an 
                operation to perform, and the iterator applies that operation to every element in the aggregate.
            &lt;/p&gt;  
            
            &lt;p&gt;
                External iterators are more flexible than internal iterators. It's easy to compare two collections for 
                equality with an external iterator, for example, but it's practically impossible with internal iterators. 
                Internal iterators are especially weak in a language like C++ that does not provide anonymous 
                functions, closures, or continuations like Smalltalk and CLOS. But on the other hand, internal iterators 
                are easier to use, because they define the iteration logic for you. 
            &lt;/p&gt;
        &lt;/blockquote&gt;
        
        &lt;p&gt;
            To make this very concrete, one might define a collection-like interface
            using external iterators like this:
        &lt;/p&gt;
        &lt;blockquote&gt;
            &lt;pre&gt;
public interface ExternalIterable&amp;lt;T&gt; {
    ExternalIterator&amp;lt;T&gt; iterator();
}
public interface ExternalIterator&amp;lt;T&gt; {
    T next();
    boolean hasNext();
}&lt;/pre&gt;
        &lt;/blockquote&gt;
        &lt;p&gt;
            On the other hand, using internal iterators one might define an interface
            something like this:
        &lt;/p&gt;
        &lt;blockquote&gt;
            &lt;pre&gt;
public interface InternalIterable&amp;lt;T&gt; {
    void iterate(Function&amp;lt;T&gt; closure);
}
public interface Function&amp;lt;T&gt; {
    void invoke(T t);
}&lt;/pre&gt;
        &lt;/blockquote&gt;
        &lt;p&gt;
            Languages with well-integrated support for closures (such as Scala, Smalltalk,
            and Ruby)
            usually provide support for looping over their collections
            using internal iterators - they are, after all, easier to use in most cases -
            while other object-oriented languages (such as C++, Java, and C#) tend to
            use external iterators. Without
            &lt;a href="http://www.javac.info"&gt;well-integrated language
            support for closures&lt;/a&gt;, internal
            iterators would be
            &lt;a href="http://www.parleys.com/display/PARLEYS/Closures%20for%20Java"&gt;
            too painful to use effectively&lt;/a&gt;.
            For that reason, the Java collection framework uses external
            iterators. But once we have &lt;a href="http://www.javac.info"&gt;closures&lt;/a&gt;
            in the language, wouldn't
            it be worth reversing that decision?
        &lt;/p&gt;
        
        &lt;p&gt;
            The answer is no, and it isn't
            just because it would be an incompatible change to an existing interface.
            As discussed above, external iterators are more flexible for some
            clients.  The simpler code that clients can write using internal
            iterators is already achieved in many clients (of external iterators)
            due to the previous addition
            of the for-each loop in JDK5. For the remaining clients, simple library
            methods can bridge the gap between internal and external iterators.
            See, for example,
            &lt;a href="http://gafter.blogspot.com/2006/10/iterative-control-abstraction-user.html"&gt; 
            the "eachEntry" method for iterating over the entries
            of a map, discussed in my earlier postings on closures&lt;/a&gt;. To see how easy
            the conversion is,
            here is the code to convert from an external iterator to an internal one:
        &lt;/p&gt;
        
        &lt;blockquote&gt;
            &lt;pre&gt;
    public &amp;lt;T&gt; InternalIterable&amp;lt;T&gt; internalize(final ExternalIterable&amp;lt;T&gt; ext) {
        return new InternalIterable&amp;lt;T&gt;() {
            public void iterate(Function&amp;lt;T&gt; closure) {
                for (ExternalIterator&amp;lt;T&gt; it = ext.iterator(); it.hasNext(); ) {
                    closure.invoke(it.next());
                }
            }
        };
    }&lt;/pre&gt;
        &lt;/blockquote&gt;
        
        &lt;p&gt;
            Iteration using internal iterators is often much easier to
            implement, because the iterator implementation doesn't have to
            explicitly store and
            manage the state of the iteration. Much of the complexity in the implementation
            of the iterators
            for Java's &lt;code&gt;HashMap&lt;/code&gt; and &lt;code&gt;TreeMap&lt;/code&gt;
            (and their &lt;code&gt;Set&lt;/code&gt; cousins)
            would simply vanish if the iterators were internal.
            For that reason, it is interesting to see if it is possible to have the iterator
            implemented internally, but exposed to the client externally, by writing a
            utility method that converts between the two iterable interfaces. 
            This is the reverse of the conversion above. How easy 
            this is to implement depends on the features of your
            programming language.
        &lt;/p&gt;
        &lt;p&gt;
            C# provides a "yield return" construct that helps provide the
            convenience of implementing internal iterators and the flexibility
            of using external iterators.  But it is not quite powerful enough to
            bridge the gap between them.  See
            &lt;a href="http://blogs.msdn.com/cyrusn/archive/2004/05/19/135367.aspx"&gt;
            notes from Cyrus Najmabadi's attempt to do so&lt;/a&gt;.
            Neither are simple (local)
            &lt;a href="http://chaoticjava.com/posts/how-to-write-iterators-really-really-fast/"&gt;
            byte-code rewriting systems&lt;/a&gt; such as
            Aviad Ben Dov's
            &lt;a href="http://chaoticjava.com/posts/category/code/java/frameworks/yielder/"&gt;
            Yielder Framework&lt;/a&gt; for Java.
            You can do it using continuations,
            &lt;a href="http://blogs.msdn.com/cyrusn/archive/2004/06/07/149893.aspx"&gt;
            coroutines, or fibers&lt;/a&gt;.
            But Java doesn't have them.
        &lt;/p&gt;
        &lt;p&gt;
            You can solve the problem in Java by resorting to the use of a separate
            thread to simulate coroutines. The result is messy and expensive,
            as each converted external iterator requires its own thread.
            &lt;a href="http://www.javac.info/Iterators.zip"&gt;Here is my implementation&lt;/a&gt;;
            can you do better?
        &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-6084980739329511130?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=6084980739329511130' title='29 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/6084980739329511130'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/6084980739329511130'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/07/internal-versus-external-iterators.html' title='Internal Versus External Iterators'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>29</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-8622646204885658308</id><published>2007-07-05T22:40:00.000-07:00</published><updated>2007-07-06T09:34:26.540-07:00</updated><title type='text'>Constructor Type Inference</title><content type='html'>&lt;p&gt;One of the ideas for improving the Java Programming Language
is
"type inference" on variable declarations. The idea is to simplify a
pattern of code that now appears in programs due to generics:&lt;/p&gt;
&lt;pre style="margin-left: 40px;"&gt;Map&amp;lt;String,List&amp;lt;Thing&amp;gt;&amp;gt; map = new HashMap&amp;lt;String,List&amp;lt;Thing&amp;gt;&amp;gt;();&lt;/pre&gt;
&lt;p&gt;surely we shouldn't have to give the same type parameters
twice?
The simplest proposal to relieve this redundancy allows&lt;/p&gt;
&lt;pre style="margin-left: 40px;"&gt;map := new HashMap&amp;lt;String,List&amp;lt;Thing&amp;gt;&amp;gt;();&lt;/pre&gt;
&lt;p&gt;This introduces the new colon-equals token and the
declaration-assignment statement. The variable appearing on the
left-hand-side of the statement is implicitly defined by this
statement, and its type is the type of the expression on the
right-hand-side. I don't like this proposal. It both goes too far and
not far enough.&lt;/p&gt;
&lt;p&gt;It goes too far in that it allows the programmer to elide the
type
in a variable declaration. The type in a variable declaration is
valuable documentation that helps the reader understand the program,
and this proposal reduces the readability of programs by allowing it to
be elided. Worse, it assigns the wrong type to the variable. Following &lt;span
 style="font-style: italic;"&gt;Effective Java&lt;/span&gt;
(first edition, item 34),
the type of a declared variable should be an interface type. This
statement form forces the variable to be of the (likely more specific)
type of the right-hand-side. Consequently, the programmer may
inadvertently depend on features of the concrete implementation class
when using the variable. That would make it more difficult to modify
the
program later by selecting a different implementation type.&lt;/p&gt;
&lt;p&gt;This syntax doesn't go far enough because the verbosity of
creating
generic classes is worth eliminating in other contexts as well.
Programmers today work around the verbosity by providing &lt;span
 style="font-style: italic;"&gt;static factory&lt;/span&gt;
methods corresponding to constructors:&lt;/p&gt;
&lt;pre style="margin-left: 40px;"&gt;static &amp;lt;K,V&amp;gt; HashMap&amp;lt;K,V&amp;gt; makeHashMap() {&lt;br /&gt;&amp;nbsp; &amp;nbsp; return new HashMap&amp;lt;K,V&amp;gt;();&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;This addresses the immediate problem:&lt;/p&gt;
&lt;pre style="margin-left: 40px;"&gt;Map&amp;lt;String,List&amp;lt;String&amp;gt;&amp;gt; map = makeHashMap();&lt;/pre&gt;
&lt;p&gt;Unfortunately, this idiom replaces one form of boilerplate (in
variable initialization) with another: trivial static factories. A
generic class is typically created more than once, so adding a single
static factory can simplify the code at every creation site. But with
language support, we can do better.&lt;/p&gt;
&lt;p&gt;I propose a new form of class instance creation expression:
&lt;/p&gt;
&lt;pre style="margin-left: 40px;"&gt;Map&amp;lt;String,List&amp;lt;Thing&amp;gt;&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&lt;/pre&gt;
&lt;p&gt;Using empty type parameters on a class instance creation
expression asks the language/compiler to perform type inference,
selecting appropriate type parameters exactly as it would in the
invocation of the equivalent trivial static factory.&lt;/p&gt;
&lt;p&gt;Type inference today works on the right-hand-side of an
assignment. I also propose that we enable this new form to be used in
more situations by improving type inference for expressions appearing
in other contexts:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;the argument of a method call&lt;/li&gt;
  &lt;li&gt;the receiver of a method call&lt;/li&gt;
  &lt;li&gt;the argument of a constructor&lt;/li&gt;
  &lt;li&gt;the argument of an alternate constructor invocation&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This would enable generic methods to be invoked in these
contexts without providing explicit type parameters.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-8622646204885658308?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=8622646204885658308' title='36 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/8622646204885658308'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/8622646204885658308'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/07/constructor-type-inference.html' title='Constructor Type Inference'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>36</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-5610187677814530305</id><published>2007-05-26T10:07:00.000-07:00</published><updated>2007-05-26T14:15:07.055-07:00</updated><title type='text'>Removing Language Features?</title><content type='html'>&lt;p&gt;As a language grows by the addition
of
features, it necessarily gets more complex. After all, you can't remove
existing language features because existing programs use those
features, but each additional feature adds complexity. Right?&lt;/p&gt;
&lt;p&gt;Fellow Googler Matt Shulman asked me a question about the &lt;a
 href="http://www.javac.info/"&gt;Closures for Java&lt;/a&gt;
specification. He observed that much of the complexity arises
because of support for checked exceptions in the spec. Things like &lt;code&gt;throws&lt;/code&gt;
type parameters, disjunctive types, and throws clauses on function
interfaces would be unnecessary without checked exceptions. Matt asked
me if we had considered if things would be simpler without all that. At
first I misunderstood his question to be referring to just the Closures
specification, so I answered that&amp;nbsp;the facility wouldn't fit
into the language as well without support for checked exceptions.&lt;/p&gt;
&lt;p&gt;Matt clarified that he was asking not just about removing
support for checked exceptions from the Closures spec, but from the
entire programming language.&lt;/p&gt;
&lt;p&gt;There has been an
&lt;a href="http://www.artima.com/intv/solid.html"&gt;ongoing&lt;/a&gt;
&lt;a href="http://www.artima.com/intv/handcuffs.html"&gt;debate&lt;/a&gt;
on the utility
of checked exceptions. Many people are critical of Java's
checked exceptions, characterizing them as a failed experiment in
software engineering. In practice, checked exceptions can result in &lt;a
 href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/InvocationTargetException.html"&gt;API
complexity&lt;/a&gt;, and programs appear to be cluttered with
exception handling code just to satisfy the compiler. Some people
believe checked exceptions are a good language
feature but are &lt;a
 href="http://dev2dev.bea.com/pub/a/2006/11/effective-exceptions.html"&gt;misused,
even in the JDK&lt;/a&gt;. With the "experts" being such poor role
models, how can we expect ordinary Java programmers to do better?&lt;/p&gt;
&lt;p&gt;We did
a &lt;a href="http://www.google.com/search?q=java+checked+exceptions"&gt;Google
search&lt;/a&gt; to see how many people have written in support of
checked exceptions and how many people don't like them. The discussion
seems to be lopsided against checked exceptions, but on the other hand
that may be due to the fact that checked exceptions are the status
quo.&lt;/p&gt;
&lt;p&gt;This isn't a question I had thought much about. I believe the
language could be simplified by treating all exception
types as unchecked without breaking existing programs. This could also
result in a simplification of future language extensions and APIs. But
would the language and platform be better off without checked
exceptions?&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-5610187677814530305?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=5610187677814530305' title='85 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/5610187677814530305'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/5610187677814530305'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/05/removing-language-features.html' title='Removing Language Features?'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>85</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-3200938110645509413</id><published>2007-05-20T19:01:00.000-07:00</published><updated>2007-05-20T19:11:51.082-07:00</updated><title type='text'>A Limitation of Super Type Tokens</title><content type='html'>&lt;p&gt;Watching Josh Bloch's presentation at JavaOne about new topics
in the second edition of &lt;a
 href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;amp;location=http%3A%2F%2Fwww.amazon.com%2FEffective-Java-Programming-Language-Guide%2Fdp%2F0201310058&amp;amp;tag=wwwgaftercom-20&amp;amp;linkCode=ur2&amp;amp;camp=1789&amp;amp;creative=9325"&gt;&lt;span
 style="font-style: italic;"&gt;Effective Java&lt;/span&gt;&lt;/a&gt;
makes me want to go out and get my own copy. Unfortunately, he's not
scheduled to have the new edition in print until later this year.&lt;/p&gt;
&lt;p&gt;There was a coincidental adjacency between two slides in
Josh's
talk that made me think a bit more about the idea of &lt;a
 href="http://gafter.blogspot.com/2006/12/super-type-tokens.html"&gt;&lt;span
 style="font-style: italic;"&gt;Super Type Tokens&lt;/span&gt;&lt;/a&gt;.
The last slide of his discussion of generics gave a complete
implementation of the mind-expanding &lt;span
 style="font-style: italic;"&gt;Typesafe Heterogenous Containers&lt;/span&gt;
(THC) pattern using Super Type Tokens:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;import&amp;nbsp;java.lang.reflect.*;&lt;br /&gt;&lt;br /&gt;public&amp;nbsp;abstract&amp;nbsp;class&amp;nbsp;TypeRef&amp;lt;T&amp;gt;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;private&amp;nbsp;final&amp;nbsp;Type&amp;nbsp;type;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;protected&amp;nbsp;TypeRef()&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;ParameterizedType&amp;nbsp;superclass&amp;nbsp;=&amp;nbsp;(ParameterizedType)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;getClass().getGenericSuperclass();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;type&amp;nbsp;=&amp;nbsp;superclass.getActualTypeArguments()[0];&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@Override&amp;nbsp;public&amp;nbsp;boolean&amp;nbsp;equals&amp;nbsp;(Object&amp;nbsp;o)&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;return&amp;nbsp;o&amp;nbsp;instanceof&amp;nbsp;TypeRef&amp;nbsp;&amp;amp;&amp;amp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;((TypeRef)o).type.equals(type);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@Override&amp;nbsp;public&amp;nbsp;int&amp;nbsp;hashCode()&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;return&amp;nbsp;type.hashCode();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public&amp;nbsp;class&amp;nbsp;Favorites2&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;private&amp;nbsp;Map&amp;lt;TypeRef&amp;lt;?&amp;gt;,&amp;nbsp;Object&amp;gt;&amp;nbsp;favorites&amp;nbsp;=&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;new&amp;nbsp;HashMap&amp;lt;&amp;nbsp;TypeRef&amp;lt;?&amp;gt;&amp;nbsp;,&amp;nbsp;Object&amp;gt;();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;public&amp;nbsp;&amp;lt;T&amp;gt;&amp;nbsp;void&amp;nbsp;setFavorite(TypeRef&amp;lt;T&amp;gt;&amp;nbsp;type,&amp;nbsp;T&amp;nbsp;thing)&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;favorites.put(type,&amp;nbsp;thing);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&lt;span
 style="color: rgb(153, 0, 0);"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@SuppressWarning("unchecked")&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;public&amp;nbsp;&amp;lt;T&amp;gt;&amp;nbsp;T&amp;nbsp;getFavorite(TypeRef&amp;lt;T&amp;gt;&amp;nbsp;type)&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;return&amp;nbsp;&lt;span
 style="color: rgb(153, 0, 0);"&gt;(T)&lt;/span&gt;&amp;nbsp;favorites.get(type);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;public&amp;nbsp;static&amp;nbsp;void&amp;nbsp;main(String[]&amp;nbsp;args)&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Favorites2&amp;nbsp;f&amp;nbsp;=&amp;nbsp;new&amp;nbsp;Favorites2();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;List&amp;lt;String&amp;gt;&amp;nbsp;stooges&amp;nbsp;=&amp;nbsp;Arrays.asList(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;"Larry",&amp;nbsp;"Moe",&amp;nbsp;"Curly");&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;f.setFavorite(new&amp;nbsp;TypeRef&amp;lt;List&amp;lt;String&amp;gt;&amp;gt;(){},&amp;nbsp;stooges);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;List&amp;lt;String&amp;gt;&amp;nbsp;ls&amp;nbsp;=&amp;nbsp;f.getFavorite(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;new&amp;nbsp;TypeRef&amp;lt;List&amp;lt;String&amp;gt;&amp;gt;(){});&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;But on the very next slide, the very first bullet of the
summary of his presentation reminds us&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Don't ignore compiler warnings.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This was referring to Josh's advice earlier in the
presentation not
to ignore or suppress unchecked compiler warnings without trying to
understand them. Ideally, you should only suppress these warnings when
you have good reason to believe that the code is type-safe, even though
you might not be able to convince the compiler of that fact.&lt;/p&gt;
&lt;p&gt;The method &lt;code&gt;Favorites2.getFavorite&lt;/code&gt;,
above, is annotated
to suppress a warning from the compiler. Without that annotation, the
compiler complains about the cast to the type T, a type parameter. Is
this code demonstrably type safe? Is it possible to cause this cast to
fail using code that is otherwise completely type safe? Unfortunately,
the cast is not safe:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;class Oops {
    static Favorites2 f = new Favorites2();

    static &amp;lt;T&amp;gt; List&amp;lt;T&amp;gt; favoriteList() {
        TypeRef&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; ref = new TypeRef&amp;lt;List&amp;lt;T&amp;gt;&amp;gt;(){};
        List&amp;lt;T&amp;gt; result = f.getFavorite(ref);
        if (result == null) {
            result = new ArrayList&amp;lt;T&amp;gt;();
            f.setFavorite(ref, result);
        }
        return result;
    }

    public static void main(String[] args) {
        List&amp;lt;String&amp;gt; ls = favoriteList();
        List&amp;lt;Integer&amp;gt; li = favoriteList();
        li.add(1);
        for (String s : ls) System.out.println(s);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;This program compiles without warning, but it exposes the
loopole in the type system created by the cast to T in&amp;nbsp;&lt;code&gt;Favorites2.getFavorite&lt;/code&gt;.
The compiler's warning does, after all, tell us about a weakness in the
type safety of the program.&lt;/p&gt;
&lt;p&gt;The issue is a subtle one: &lt;code&gt;TypeRef&lt;/code&gt;
treats two types as the same when the underlying &lt;code&gt;java.lang.reflect.Type&lt;/code&gt;
objects are equal. A given &lt;code&gt;java.lang.reflect.Type&lt;/code&gt;
object represents a particular &lt;span style="font-style: italic;"&gt;static&lt;/span&gt;
type appearing in the source, but if it is a type variable it can
represent a different &lt;span style="font-style: italic;"&gt;dynamic&lt;/span&gt;
type &lt;span style="font-style: italic; text-decoration: underline;"&gt;&lt;span
 style="font-style: italic;"&gt;&lt;/span&gt;&lt;/span&gt;from
one point in the program's execution to another. The program &lt;code&gt;Oops&lt;/code&gt;
exploits that mismatch.&lt;/p&gt;
&lt;p&gt;The Super Type Token pattern can be redeemed by disallowing
the use of type variables anywhere in the Type object it stores. That
can be enforced at runtime (but not at compile time) in the constructor.&lt;/p&gt;
&lt;p&gt;Perhaps a better solution would be to &lt;a
 href="http://gafter.blogspot.com/2006/11/reified-generics-for-java.html"&gt;reify
generics&lt;/a&gt; (i.e., "&lt;a
 href="http://www.artima.com/forums/flat.jsp?forum=121&amp;amp;thread=192309"&gt;erase
erasure&lt;/a&gt;") in the language, making all this nonsense
unnecessary.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-3200938110645509413?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=3200938110645509413' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3200938110645509413'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3200938110645509413'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/05/limitation-of-super-type-tokens.html' title='A Limitation of Super Type Tokens'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-6347967251520208521</id><published>2007-04-27T09:12:00.000-07:00</published><updated>2007-04-27T09:15:10.286-07:00</updated><title type='text'>A Consensus Closures JSR Proposal</title><content type='html'>&lt;p&gt;I had set aside work on the closures prototype for a couple of
months to write a JSR proposal that represents a consensus among the
folks thinking about this area. You can find it at &lt;a
 href="http://www.javac.info/consensus-closures-jsr.html"&gt;http://www.javac.info/consensus-closures-jsr.html&lt;/a&gt;.
One of the things I learned is that unanimous agreement is rarely
possible. There are those who feel that nothing should be done to the
Java programming language, and such people will not be swayed by simple
but powerful additions. Our latest JSR proposal comes as close to
achieving consensus as I believe possible. All but one of
the authors of the three widely-discussed closures proposals
have agreed to support it.&lt;/p&gt;
&lt;p&gt;The purpose of the JSR proposal is to define the problems to
be solved and circumscribe the permitted solution space. It doesn't
mandate a particular solution, though it does offer the &lt;a
 href="http://www.javac.info/"&gt;&lt;span
 style="font-style: italic;"&gt;Closures for Java&lt;/span&gt;&lt;/a&gt;
specification as an example of a solution to many (but not all) of the
problems. This should not be surprising, as that spec was written
specifically in an attempt to satisfy the requirements. Still, the spec
is a work in progress.&lt;/p&gt;
&lt;p&gt;So what is next? I hope we'll have some active discussion at
JavaOne about where to go from here.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-6347967251520208521?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=6347967251520208521' title='12 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/6347967251520208521'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/6347967251520208521'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/04/consensus-closures-jsr-proposal.html' title='A Consensus Closures JSR Proposal'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>12</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-5793928125436653523</id><published>2007-03-29T02:09:00.000-07:00</published><updated>2007-03-29T02:12:58.100-07:00</updated><title type='text'>Closures for Organizing Your Code</title><content type='html'>&lt;p&gt;Much of the discussion of Closures in Java has been about they way they affect public APIs. But there is another aspect  that is just as important: the way closures affect &lt;em&gt;private&lt;/em&gt; APIs between parts of your program. Closures often enable a tremendous simplification of a program design compared to what would be required in their absence. The following describes my implementation of a graph algorithm for computing the&lt;em&gt; Jeffersonians&lt;/em&gt; of a graph using algorithm K from Knuth's &lt;em&gt;The Art of Computer Programming&lt;/em&gt;, volume 4B, section 7.5.7.&lt;/p&gt;
&lt;p&gt;As you may be aware the set of Jeffersonians of a graph is best computed using a complex recursive algorithm. Although recursive algorithms can be translated into algorithms without using recursion (Java without recursion remains Turing-complete), the recursive version of the algorithm is much shorter and easier to understand. We're lucky to be living in an age in which virtually all programming languages support recursion. Though details of the implementation are not important, my implementation went something like this:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;public Collection&amp;lt;Jeffersonian&amp;gt; findAllJeffersonians(Graph g) {
    Collection&amp;lt;Jeffersonian&amp;gt; result = new ArrayList&amp;lt;Jeffersonian&amp;gt;();
    findAllJeffersoniansInternal(g, result);
    return result;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;The idea is that the recursive part of the algorithm can pass around the collection into which the result will be placed, and every Jeffersonian that is found will be placed into the collection:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;private void findAllJeffersoniansInternal(&lt;br /&gt;        Graph g, Collection&amp;lt;Jeffersonian&amp;gt; result) {&lt;br /&gt;    // complex recursive algorithm here&lt;br /&gt;    Jeffersonian found = ...;&lt;br /&gt;    result.add(found);&lt;br /&gt;    // more complex recursion here&lt;br /&gt;}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;One pot of coffee and an all-nighter later I had this working like a charm. The next day my  tech lead asked me to add an API element that determines whether or not a graph has a Jeffersonian or not. That was easy:&lt;/p&gt;
  
&lt;blockquote&gt;
  &lt;pre&gt;public boolean hasJeffersonian(Graph g) {
    return findAllJeffersonians(g).size() != 0;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;This didn't pass code review. The problem is that this new method is to be used in the inner loop of Google's &amp;uuml;ber-secret application that will take over the world. Never mind that. The problem is performance. Determining whether or not a graph &lt;em&gt;has&lt;/em&gt; a Jeffersonian can be done in linear time, but  enumerating all of them requires quadratic time (or worse). But my implementation does it the hard way. By then it was Friday afternoon and I really wanted to head home for a glass of wine, so I did what any self-loathing software engineer would do: I cut and pasted the complex recursive code in &lt;tt&gt;findAllJeffersoniansInternal&lt;/tt&gt; into &lt;tt&gt;hasJeffersonianInternal&lt;/tt&gt; and added a boolean return value (true when a Jeffersonian was found). Then I added logic to short-circuit the rest of the algorithm once a Jeffersonian had been found at any step. The code was messy but workable, and I had it passing tests in less than an hour. The code duplication left me somewhat uncomfortable, but the two methods were different enough that merging them would have been hard. I considered adding a second flag so I could have one body of code to do both versions, but I decided to leave that refactoring until Monday. &lt;/p&gt;
    &lt;p&gt;Something very strange happened over the weekend, though. On Monday my pointy-haired boss told me there was both good news and bad news, and asked which I wanted first. Knowing how these jokes work (the second one always trumps the first) I asked for the bad news first. The bad news was that my machine had crashed, losing all of my work from Friday. Including my implementation of &lt;tt&gt;hasJeffersonian&lt;/tt&gt;. The good news was that my machine had been replaced with a brand new one, a fast new 40-core workstation, and it came with JDK7 preinstalled. I had been using JDK6 before, so I was eager to try  the new Java language features. &lt;/p&gt;
    &lt;p&gt;Taking a fresh look at the problem of writing &lt;tt&gt;hasJeffersonian&lt;/tt&gt;, I decided to refactor the original program to pass  a closure instead of a collection:&lt;/p&gt;
    &lt;blockquote&gt;
      &lt;pre&gt;public Collection&amp;lt;Jeffersonian&amp;gt; findAllJeffersonians(Graph g) {
    Collection&amp;lt;Jeffersonian&amp;gt; result = new ArrayList&amp;lt;Jeffersonian&amp;gt;();
    findAllJeffersoniansInternal(g, { Jeffersonian j =&amp;gt; result.add(j); });
    return result;
}&lt;br /&gt;&lt;br /&gt;private void findAllJeffersoniansInternal(&lt;br /&gt;        Graph g, {Jeffersonian =&amp;gt; void} foundJeffersonian) {&lt;br /&gt;    // complex recursive algorithm here&lt;br /&gt;    Jeffersonian found = ...;&lt;br /&gt;    foundJeffersonian.invoke(found);&lt;br /&gt;    // more complex recursion here&lt;br /&gt;}&lt;/pre&gt;
&lt;/blockquote&gt;
    &lt;p&gt;Then I realized I could use the nicer syntax allowed for passing a closure to a method:&lt;/p&gt;
    &lt;blockquote&gt;
      &lt;pre&gt;public Collection&amp;lt;Jeffersonian&amp;gt; findAllJeffersonians(Graph g) {
    Collection&amp;lt;Jeffersonian&amp;gt; result = new ArrayList&amp;lt;Jeffersonian&amp;gt;();
    findAllJeffersoniansInternal(Jeffersonian j : g) {
        result.add(j);
    }
    return result;
}&lt;/pre&gt;
    &lt;/blockquote&gt;
    &lt;p&gt;Solving the second problem was then trivial:&lt;/p&gt;
    &lt;blockquote&gt;
      &lt;pre&gt;public boolean hasJeffersonian(Graph g) {
    findAllJeffersoniansInternal(Jeffersonian j : g) {&lt;br /&gt;        return true;&lt;br /&gt;    }
    return false;
}&lt;/pre&gt;
    &lt;/blockquote&gt;
    &lt;p&gt;That was the entire implementation. I had a strange sense of elation, but I couldn't quite tell why. I could no longer remember why the problem was so messy on Friday. This refactoring seemed trivial, and this code was so clear. What made it so hard before? &lt;/p&gt;
    &lt;p&gt;Then I woke up. It's 2007, not 2009. JDK7 is barely a gleam in the eye of Sun. My machine is only dual-core. Consensus on closures is elusive. As far as I can tell, there isn't any such thing as a graph's Jeffersonian, or a Google plan to take over the world. It's Monday morning, and I have to figure out how to merge two  almost-copies of a big recursive algorithm.&lt;/p&gt;
    &lt;p&gt;But on the bright side, my boss is a really nice guy.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-5793928125436653523?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=5793928125436653523' title='27 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/5793928125436653523'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/5793928125436653523'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/03/closures-for-organizing-your-code.html' title='Closures for Organizing Your Code'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>27</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-1766267659475005758</id><published>2007-03-16T16:39:00.000-07:00</published><updated>2007-03-16T16:41:17.639-07:00</updated><title type='text'>A Compact Object Comparator</title><content type='html'>&lt;p&gt;Every now and then a problem arises where the right solution would be to impose an arbitrary total ordering on a collection of objects. The simplest example of this is when you need to sychronize on more than one object, all at the same time, to maintain some consistency condition across those objects. Using &lt;a href="http://www.javac.info/"&gt;Closures&lt;/a&gt;, you might invoke a utility method like this: &lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;Locks.withLocks(lock1, lock2) {
    // code protected by both locks
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;To avoid deadlock, every piece of code that locks the same set of locks should do so in the same order. Rather than forcing all callers of the &lt;code&gt;withLocks&lt;/code&gt; method to worry about getting them in the right order, the implementation of &lt;code&gt;withLocks&lt;/code&gt; can sort the incoming locks. Then the caller can just pass the locks in arbitrary order, knowing that they will be locked &amp;quot;in the right order&amp;quot;. It doesn't actually matter what order we sort them in, as long as we always get the same order for the same objects. The implementation of &lt;code&gt;withLocks&lt;/code&gt; can use &lt;code&gt;Collections.sort&lt;/code&gt; to sort the incoming locks, but &lt;code&gt;java.util.concurrent.locks.Lock&lt;/code&gt; is not naturally comparable, so we need to pass an appropriate comparator to &lt;code&gt;sort&lt;/code&gt;. We need a &lt;code&gt;java.util.Comparator&amp;lt;Lock&amp;gt;&lt;/code&gt;, but a &lt;code&gt;java.util.Comparator&amp;lt;Object&amp;gt;&lt;/code&gt; would work just as well. Let's specify, and then implement, a suitable comparator. Here is what we need:&lt;/p&gt;
&lt;blockquote&gt;
    &lt;pre&gt;/**
 * Returns a comparator that imposes a complete order on all objects.
 * Each invocation of this method may yield a distinct comparator,
 * or may yield the same comparator.
 */
public Comparator&amp;lt;Object&amp;gt; totalOrder() { ... }&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;How are we going to do this? One idea is to create an assignment of long values to each object, as needed. That would look something like this: 
&lt;blockquote&gt;
  &lt;p&gt;
  &lt;pre&gt;public Comparator&amp;lt;Object&amp;gt; totalOrder() { return new TotalOrder(); }
private class TotalOrder implements Comparator&amp;lt;Object&amp;gt; {
    long nextNonce = 1;
    Map&amp;lt;Object,Long&amp;gt; codes = new IdentityHashMap&amp;lt;Object,Long&amp;gt;();
    public int compare(Object o1, Object o2) {
        Long l1 = getNonce(o1);
        Long l2 = getNonce(o2);
        return l1.compareTo(l2);
    }
    synchronized Long getNonce(Object o) {
        Long nonce = codes.get(o);
        if (nonce == null) {
            nonce = nextNonce++;
            codes.put(o, nonce);
        }
        return nonce;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;There are two major problems with this approach. First, it causes object retention. Objects whose space would otherwise be recovered by the garbage collector are retained because they are reachable as keys in the &lt;code&gt;codes&lt;/code&gt; map. We can't fix this by simply using a &lt;code&gt;WeakHashMap&lt;/code&gt;; without the identity semantics of &lt;code&gt;IdentityHashMap&lt;/code&gt; the technique doesn't work. We really need &lt;code&gt;WeakIdentityHashMap&lt;/code&gt; for this, but no such class exists in the JDK yet. Fortunately, &lt;a href="http://crazybob.org/"&gt;&amp;quot;crazy&amp;quot; Bob Lee&lt;/a&gt; has come to the rescue with an &lt;a href="http://google-guice.googlecode.com/svn/trunk/src/com/google/inject/util/ReferenceMap.java"&gt;implementation of this concept &lt;/a&gt; inside the recently open-sourced &lt;a href="http://code.google.com/p/google-guice/"&gt;Guice dependency injection framework&lt;/a&gt;. I think this belongs in the JDK, and now is the time to propose it for JDK7. &lt;/p&gt;
&lt;p&gt;The other problem with this implementation is that this utility takes up  too much space. In general, every time you call the &lt;code&gt;compare&lt;/code&gt; method one or two objects might be created and added to the map.&lt;/p&gt;
&lt;p&gt;Another idea for implementing this utility is to sort the objects based on their &lt;em&gt;identity hash code&lt;/em&gt;. Identity hash codes are well distributed, almost like random numbers. That is naturally thread-safe, and would look something like this: &lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;
  &lt;pre&gt;private class TotalOrder implements Comparator&amp;lt;Object&amp;gt; {
    public int compare(Object o1, Object o2) {
        if (o1==o2) return 0;
        int i1 = System.identityHashCode(o1);
        int i2 = System.identityHashCode(o2);
        return (i1&amp;lt;i2) ? -1 : (i1==i2) ? 0 : 1;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;This is much more compact than the previous approach. But because identity has codes are not guaranteed to be unique, it occasionally treats two distinct objects as equal.&lt;/p&gt;
&lt;p&gt;We can get the best of both worlds - a space-efficient comparator and a complete order - by combining the two approaches:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;
&lt;pre&gt;private class TotalOrder implements Comparator&amp;lt;Object&amp;gt; {
    long nextNonce = 1;
    Map&amp;lt;Object,Long&amp;gt; codes = new IdentityHashMap&amp;lt;Object,Long&amp;gt;();
    synchronized Long getNonce(Object o) {
        Long nonce = codes.get(o);
        if (nonce == null) {
            nonce = nextNonce++;
            codes.put(o, nonce);
        }
        return nonce;
    }
    public int compare(Object o1, Object o2) {
        if (o1==o2) return 0;
        int i1 = System.identityHashCode(o1);
        int i2 = System.identityHashCode(o2);
        if (i1 != i2) return (i1&amp;lt;i2) ? -1 : 1;
        Long l1 = getNonce(o1);
        Long l2 = getNonce(o2);
        return l1.compareTo(l2);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;By the way, if you haven't already checked it out, see &lt;a href="http://crazybob.org/"&gt;&amp;quot;crazy&amp;quot; Bob Lee&lt;/a&gt;'s &lt;a href="http://code.google.com/p/google-guice/"&gt;Guice dependency injection framework&lt;/a&gt;. We use it extensively at Google. By really taking advantage of recent language features such as generics and annotations, the Guice framework is very flexible and yet much &lt;a href="http://code.google.com/p/google-guice/wiki/SpringComparison"&gt;simpler than existing frameworks&lt;/a&gt;. &lt;a href="http://stuffthathappens.com/blog/2007/03/09/guicy-good/"&gt;Throw away your XML&lt;/a&gt; and write your Java code in Java! &lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;&lt;font size=small&gt;thanks to &lt;a href="http://crazybob.org/"&gt;&amp;quot;crazy&amp;quot; Bob Lee&lt;/a&gt; for contributing the Guice framework, and for reviewing this essay. &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-1766267659475005758?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=1766267659475005758' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/1766267659475005758'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/1766267659475005758'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/03/compact-object-comparator.html' title='A Compact Object Comparator'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-1186772807314868796</id><published>2007-03-08T08:05:00.000-08:00</published><updated>2007-03-08T08:08:06.736-08:00</updated><title type='text'>On The Expressive Power of Programming Languages</title><content type='html'>&lt;p&gt;There are  at least three separate proposals recently put forward in the space of &amp;quot;Closures for Java.&amp;quot; Among the criteria for evaluating the proposals, I'd like to discuss two: &lt;em&gt;conciseness&lt;/em&gt; (possibly phrased as &lt;em&gt;convenience&lt;/em&gt;) of  code using the construct, and &lt;em&gt;expressiveness&lt;/em&gt;. Conciseness is pretty obvious, and you can compare the proposals on this measure by writing snippets of code that do basically the same thing as each other, but written using existing constructs and then each of the proposed constructs. How many characters, or tokens, does it take to write the code? By the measure of conciseness, shorter is better. &lt;/p&gt;
&lt;p&gt;Unfortunately, the authors of the various proposals don't appear to be using a common meaning for &amp;quot;expressiveness&amp;quot; or &amp;quot;expressive power.&amp;quot; Consequently, we often end up talking at cross-purposes when comparing the proposals. Some people appear to treat &amp;quot;expressiveness&amp;quot; and &amp;quot;conciseness&amp;quot; as synonyms, but to me these have completely different meanings. Expressiveness is a bit harder to measure, but in some ways more important at this stage of the discussion. See Matthias Felleisen's, &lt;em&gt;On the Expressive Power of Programming Languages&lt;/em&gt;,   3rd European Symposium on Programming, Copenhagen, Denmark, 1990, &lt;a href="http://citeseer.ist.psu.edu/felleisen90expressive.html"&gt;http://citeseer.ist.psu.edu/felleisen90expressive.html&lt;/a&gt;, for one attempt to formally capture the meaning of expressiveness.&lt;/p&gt;
&lt;p&gt;In my mind, a language construct is &lt;em&gt; expressive&lt;/em&gt; if it enables you to write (and use) an API that can't be written (and used) without the construct. In the context of the &lt;em&gt;&lt;a href="http://www.javac.info/"&gt;Closures for Java&lt;/a&gt;&lt;/em&gt; proposed language extension, &lt;a href="http://www.bejug.org/confluenceBeJUG/display/PARLEYS/Closures+for+Java"&gt;control abstraction APIs&lt;/a&gt; are the kind of thing that don't seem to be supported by the competing proposals. You don't see the proposals compared side-by-side on this measure because this is something only supported by one proposal. Programmers who have become accustomed to programming with closures find them very useful for factoring out common code in ways that are not currently possible in Java. See, for example,  &lt;a href="http://www.joelonsoftware.com/items/2006/08/01.html" rel="nofollow"&gt;http://www.joelonsoftware.com/items/2006/08/01.html&lt;/a&gt;, &lt;a href="http://ivan.truemesh.com/archives/000637.html" rel="nofollow"&gt;http://ivan.truemesh.com/archives/000637.html&lt;/a&gt;, &lt;a href="http://www.talios.com/dear_java_i_need_closure.htm" rel="nofollow"&gt;http://www.talios.com/dear_java_i_need_closure.htm&lt;/a&gt;, and &lt;a href="http://blog.moertel.com/articles/2005/08/30/closures-and-the-professional-programmer" rel="nofollow"&gt;http://blog.moertel.com/articles/2005/08/30/closures-and-the-professional-programmer&lt;/a&gt;. These kinds of uses might not occur to you if you're mainly a Java programmer, because Java doesn't reward you for thinking this way. But this is another example of expressive power. &lt;/p&gt;
&lt;p&gt;I'm not particularly attached to one  syntax or another for closures. I don't mean to say that syntax isn't important. Anyone who knows the story of &lt;em&gt;&lt;a href="http://www.daimi.au.dk/~plesner/variance/"&gt;variance&lt;/a&gt;&lt;/em&gt; and &lt;em&gt;&lt;a href="http://www.gafter.com/~neal/jot-wildcards.pdf"&gt;wildcards&lt;/a&gt;&lt;/em&gt; knows how much I value a good surface syntax. Our proposal describes a particular syntax not because we  believe it is the best possible syntax, but because it is hard to write a specific proposal without &lt;em&gt;some&lt;/em&gt; syntax. Ultimately, I hope the closures issue becomes a JSR and the expert group takes its time to decide what surface syntax is best. But I believe that the expressiveness of the &lt;a href="http://www.javac.info/"&gt;Closures for Java&lt;/a&gt; proposal is the most important reason to consider doing anything in this space at all. If it is just a matter of a slightly more concise syntax, I'm not sure it is worth the trouble. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-1186772807314868796?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=1186772807314868796' title='13 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/1186772807314868796'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/1186772807314868796'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/03/on-expressive-power-of-programming.html' title='On The Expressive Power of Programming Languages'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>13</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-5778577199465199188</id><published>2007-03-05T21:24:00.000-08:00</published><updated>2007-03-05T21:26:34.891-08:00</updated><title type='text'>Java Closures versus MouseListener</title><content type='html'>&lt;p&gt;The &lt;a href="http://www.javac.info/"&gt;Closures for Java&lt;/a&gt; proposal simplifies the code for many purposes  where anonymous class instance creation expressions are currently used. When the anonymous class's supertype is an interface with a single abstract method, a closure can be used directly. But if the supertype is a class, like &lt;tt&gt;java.util.TimerTask&lt;/tt&gt;, or has more than one method, like &lt;tt&gt;java.awt.event.MouseListener&lt;/tt&gt;, then you can't use a closure directly. You can still use an anonymous inner class directly, as always, but there are ways of using  closures that may be more convenient. For &lt;tt&gt;TimerTask&lt;/tt&gt;, a client can be written this way &lt;br /&gt;
&lt;/p&gt;
&lt;pre&gt;&lt;blockquote&gt;void printHelloAfterDelay(java.util.Timer timer, long delay) {
    timer.schedule(TimerTask.of({ =&amp;gt; System.out.println(&amp;quot;Hello&amp;quot;); }), delay);
}&lt;/blockquote&gt;&lt;/pre&gt;

&lt;p&gt;if we add  the following utility method to &lt;tt&gt;TimerTask&lt;/tt&gt;: &lt;/p&gt;
&lt;pre&gt;&lt;blockquote&gt;&lt;p&gt;public TimerTask of(final Runnable block) {
    class ClosureTimerTask extends TimerTask {&lt;br /&gt;        public void run() { block.run(); }&lt;br /&gt;    }&lt;br /&gt;    return new ClosureTimerTask();
}&lt;/p&gt;&lt;/blockquote&gt;&lt;/pre&gt;

&lt;p&gt;Similarly, Peter von der Ah&amp;eacute; showed me how to use the builder pattern, along with closures, to simplify handling mouse events:&lt;/p&gt;

&lt;pre&gt;&lt;blockquote&gt;void addSomeActions(java.awt.Component foo) {
    foo.addMouseListener(new MouseListenerBuilder() 
        .setMouseClicked({ MouseEvent e =&gt; System.out.println("Mouse clicked"); })
        .setMouseReleased({ MouseEvent e =&gt; System.out.println("Mouse released"); })
        .setMouseEntered({ MouseEvent e =&gt; System.out.println("Mouse entered " + e.getComponent()); }));
}&lt;/blockquote&gt;&lt;/pre&gt;

&lt;p&gt;The implementation of &lt;tt&gt;MouseListenerBuilder&lt;/tt&gt; is left as an exercise to the reader. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-5778577199465199188?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=5778577199465199188' title='13 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/5778577199465199188'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/5778577199465199188'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/03/java-closures-versus-mouselistener.html' title='Java Closures versus MouseListener'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>13</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-1935140630697961689</id><published>2007-02-05T10:33:00.000-08:00</published><updated>2008-01-31T09:29:01.493-08:00</updated><title type='text'>Closures Spec Update (v0.5)</title><content type='html'>&lt;span style="font-style:italic;"&gt;This post discusses a draft proposal for adding support for closures to the Java programming language for the Dolphin (JDK 7) release. It was carefully designed to interoperate with the current idiom of one-method interfaces. The latest version of the proposal and a prototype can be found at &lt;a href="http://www.javac.info/"&gt;http://www.javac.info/&lt;/a&gt;.&lt;/span&gt;
&lt;p&gt;We've just updated the &lt;a href="http://www.javac.info/"&gt;Closures for Java specification&lt;/a&gt;, bringing it to v0.5. There are two significant changes:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;We've dropped the &lt;em&gt;nominal&lt;/em&gt; version of the specification. We are no longer maintaining parallel versions of the specification (with and without function types) because the most significant concerns regarding function types were resolved in earlier revisions of the spec.&lt;/li&gt;
  &lt;li&gt;We added support for user-defined looping APIs. I wrote about this in &lt;a href="http://gafter.blogspot.com/2006/10/iterative-control-abstraction-user.html"&gt;October 2006&lt;/a&gt;, but did not integrate that into the spec until now. &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;There is now a &lt;a href="http://video.google.com/videoplay?docid=4051253555018153503"&gt;two-hour version of my Closures for Java talk&lt;/a&gt; on video. It is the same as the &lt;a href="http://www.bejug.org/confluenceBeJUG/display/PARLEYS/Closures+for+Java"&gt;one-hour version&lt;/a&gt; but with questions and answers both during  and after the talk. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-1935140630697961689?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=1935140630697961689' title='25 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/1935140630697961689'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/1935140630697961689'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/02/closures-spec-update-v05.html' title='Closures Spec Update (v0.5)'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>25</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-4321764360411487609</id><published>2007-01-28T14:11:00.000-08:00</published><updated>2011-07-06T16:42:55.690-07:00</updated><title type='text'>A Definition of Closures</title><content type='html'>&lt;p&gt;There has been some confusion over our proposal to add closures to the Java Programming Language. After all, doesn't Java already have closures in the form of anonymous inner classes? What is the point of adding something to the language that it already has? To some there appears to be a lot in the proposal that has nothing to do with closures, including the control invocation syntax, &lt;tt&gt;null&lt;/tt&gt; as a type, &lt;tt&gt;Unreachable&lt;/tt&gt;, &lt;tt&gt;throws&lt;/tt&gt; type parameters, function interface types, and &amp;quot;nonlocal&amp;quot; returns. In my Javapolis talk I tried to give an explanation for why these features are in the proposal from the practical point of view of what kinds of things would be possible that were not formerly possible. But that begs the question: why do we call it &amp;quot;Closures&amp;quot; for Java? In this blog post I'll try to show how the definition of closures relates to the features of the proposal, and identify which features of the proposal do (and which do not) result from the definition. &lt;/p&gt;
&lt;p&gt;Before discussing the definition of closures, it helps to understand the historical context in which the term was introduced. &lt;/p&gt;
&lt;p&gt;&lt;a href="http://www-formal.stanford.edu/jmc/history/lisp/lisp.html"&gt;Lisp was created&lt;/a&gt; in the late 1950's by John McCarthy and others at M.I.T. One feature of the language was function-valued expressions, signified by &lt;em&gt;lambda&lt;/em&gt;. The name &amp;quot;lambda&amp;quot; was borrowed from a mathematical formalism known as the lambda calculus. Although Lisp was not based on an effort to model that formalism, lambda  plays approximately the same role in Lisp as it does in the lambda calculus:  lambda  is the syntax for a function-valued expression. McCarthy's intent was that Lisp should be designed to be implemented very efficiently, ideally compiled. That desire for efficiency influenced the design of the language. &lt;/p&gt;
&lt;p&gt;Lisp used something called &lt;em&gt;dynamic scoping&lt;/em&gt;. Logically, in a dynamically scoped language, when a variable  reference is evaluated the runtime looks up the call stack until it finds a scope in which a variable of that name is defined. But as a practical matter variable references in a dynamically scoped language can be resolved in constant time simply by maintaining a value cell for each variable name; that value cell  caches the variable's current definition. Dynamic scoping is   easy to implement in an interpreter or compiler. Some very clever people had found ways to not only take advantage of dynamic scoping, but had developed what would now be thought of as programming patterns that depended deeply on it. But it was soon discovered that dynamic scoping suffered subtle  problems, something the Lisp community called the &lt;a href="http://portal.acm.org/citation.cfm?id=1093411"&gt;&lt;em&gt;FUNARG problem&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now we fast-forward to the mid 1970's. On the radio you would hear&lt;sup&gt;1&lt;/sup&gt; &lt;a href="http://www.amazon.com/gp/product/B00006RAKP?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00006RAKP"&gt;Elton John&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B00004YR27?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00004YR27"&gt;Emerson Lake &amp;amp; Palmer&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B000002N9Z?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B000002N9Z"&gt;Joni Mitchell&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B00005J73Z?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00005J73Z"&gt;The Captain and Tennille&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B0002WZT4S?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B0002WZT4S"&gt;John Denver&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B00006LI2R?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00006LI2R"&gt;Paul Simon&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B00000721P?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00000721P"&gt;Paul McCartney and Wings&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B00005QJFL?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00005QJFL"&gt;ABBA&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B00006JYI7?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00006JYI7"&gt;David Bowie&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B0002QPRSM?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B0002QPRSM"&gt;Janis Ian&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B000068QZI?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B000068QZI"&gt;Aerosmith,&lt;/a&gt; &lt;a href="http://www.amazon.com/gp/product/B00009RAJI?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00009RAJI"&gt;Fleetwood Mac&lt;/a&gt;, &lt;a href="http://www.amazon.com/gp/product/B00000ADGH?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B00000ADGH"&gt;Heart&lt;/a&gt;, and &lt;a href="http://www.amazon.com/gp/product/B000000OF6?ie=UTF8&amp;amp;tag=wwwgafterco07-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=B000000OF6"&gt;Queen&lt;/a&gt;. A number of popular Lisp dialects were in use including InterLisp, MacLisp, UCI-Lisp, Stanford Lisp 1.6, and U. Utah's Standard Lisp. All of them were dynamically scoped. It was in this context that &lt;a href="https://dspace.mit.edu/bitstream/1721.1/6913/2/AITR-474.pdf"&gt;Guy Steele and Gerald Jay Sussman developed&lt;/a&gt; &lt;em&gt;&lt;a href="http://scholar.google.com/scholar?hl=en&amp;amp;lr=&amp;amp;cluster=4566527396222999701"&gt;Scheme&lt;/a&gt;&lt;/em&gt;,  a very simple Lisp dialect.&lt;/p&gt;
&lt;p&gt;One thing about Scheme was different&lt;sup&gt;2&lt;/sup&gt;. Scheme was &lt;em&gt;lexically scoped&lt;/em&gt;, like the lambda calculus and most mathematical notations, which means that  a variable reference &lt;em&gt;binds&lt;/em&gt; to the &lt;em&gt;lexically&lt;/em&gt; enclosing definition for that name that was active at the time the enclosing lambda form was evaluated. To explain the semantics in terms of the implementation, evaluating a lambda expression was said to produce a &lt;strong&gt;&lt;em&gt;closure&lt;/em&gt;&lt;/strong&gt;. This is a function value represented as   an object that contains references to the  current bindings for all the variables used inside the lambda expression but defined outside it. These are called the &lt;em&gt;free variables&lt;/em&gt;.  When this closure object, or &lt;em&gt;function&lt;/em&gt;, is applied to arguments later, the variable bindings that had been captured in the closure  are used to give meaning to the free variables appearing in the code. The term closure describes more than just the abstract language construct, it also describes its implementation. &lt;/p&gt;
&lt;p&gt;To many in the Lisp community at the time, it didn't make sense to adopt a Lisp dialect with closures. Not only would it undermine common programming techniques but it would obviously be much less efficient. For a short time these issues were debated, and Guy Steele wrote a &lt;a href="http://library.readscheme.org/page1.html"&gt;series of papers&lt;/a&gt; entitled &lt;em&gt;Lambda the Ultimate _____&lt;/em&gt; (where _____ is &lt;a href="http://scholar.google.com/scholar?hl=en&amp;amp;lr=&amp;amp;cluster=6756466485684414379"&gt;&lt;em&gt;Imperative&lt;/em&gt;&lt;/a&gt;, &lt;a href="http://scholar.google.com/scholar?hl=en&amp;amp;lr=&amp;amp;cluster=14654998121301205850"&gt;&lt;em&gt;Declarative&lt;/em&gt;&lt;/a&gt;, &lt;a href="http://scholar.google.com/scholar?hl=en&amp;amp;lr=&amp;amp;cluster=4529162033070730978"&gt;&lt;em&gt;GOTO&lt;/em&gt;&lt;/a&gt;, or &lt;a href="http://scholar.google.com/scholar?hl=en&amp;amp;lr=&amp;amp;cluster=10861623814207912570"&gt;&lt;em&gt;Opcode&lt;/em&gt;&lt;/a&gt;) to   help explain the power of lexically scoped lambda (closures). Fast forward only a few years and the debate was largely settled: lexical scoping is Right and dynamic scoping is Wrong and we've all learned our lesson. Since that time the word &lt;em&gt;closure&lt;/em&gt; is used to mean lexically scoped anonymous function, but the connotation is that it is possible to get the semantics wrong for any number of reasons, including  bugs and concerns about implementation efficiency. It also hints that we should let the language design drive the implementation, not the other way around. Virtually every programming language, whether or not it has something like lambda and anonymous function values, uses lexical rather than dynamic scoping. The basic definition of a closure, however, shows its Lisp roots:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;A &lt;em&gt;closure&lt;/em&gt; is a &lt;em&gt;function&lt;/em&gt; that captures the &lt;em&gt;bindings&lt;/em&gt; of &lt;em&gt;free variables&lt;/em&gt; in its &lt;em&gt;lexical context&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Around this time,  &lt;a href="http://gagne.homedns.org/~tgagne/contrib/EarlyHistoryST.html"&gt;Smalltalk was introduced&lt;/a&gt;. Smalltalk is the most pure and simple of the object-oriented languages: everything is an object. Object-oriented languages add a  twist to lexical scoping. Rather than binding all names in the lexical scope,  free variables appearing in &lt;em&gt;methods&lt;/em&gt; are bound in the scope of the object that the method is a member of. In other words,  names  in a method are bound to members of the &amp;quot;current&amp;quot; object. The current object is accessible by the name &amp;quot;self&amp;quot;. Another small but interesting detail is that you can return early from a method in Smalltalk using the syntax &amp;quot;^&lt;em&gt;expression&lt;/em&gt;&amp;quot;. We'll return (no pun intended) to the significance of this fact later.   &lt;/p&gt;
&lt;p&gt;Methods aren't the only kind of code abstraction in Smalltalk. There is also an expression form for writing a &lt;em&gt;block&lt;/em&gt; expression, which is essentially a lambda. Early dialects had limitations on them, but  most modern Smalltalks do not. They are a true analog to Scheme's lambda. Free variables in a Smalltalk block are bound in the enclosing scope, which is typically the scope of some enclosing method. The result of evaluating a block expression is a closure, and like everything else it is an object. In this case the object has a method that you use to invoke the code of the block.&lt;/p&gt;
&lt;p&gt;Anonymous functions  (closures) were not blindly introduced into Smalltalk just because it seemed like a neat idea, or because they had worked out well in another language. Rather they were integrated fully and carefully into the  language. Anonymous functions can properly be integrated into even an existing language, but there is an advantage when adding them early. As Guy Steele's papers demonstrated, they are so powerful that they subsume other language features. If you add them early, you might save yourself the trouble of adding language features that can instead be added as libraries. Smalltalk provides few control constructs directly in the language. Even the conditional &amp;quot;if&amp;quot; is provided as a library method and invoked using blocks. &lt;/p&gt;
&lt;p&gt;Two things distinguish blocks in Smalltalk from Scheme's lambda. First, the meaning of &amp;quot;self&amp;quot; within a block refers to whatever meaning it had in the enclosing context. Specifically, it doesn't refer to the closure object itself. Second, the syntax for returning from a method, &amp;quot;^&lt;em&gt;expression&lt;/em&gt;&amp;quot;, returns from the enclosing method; it doesn't return from the method representing the closure invocation. These two details are a natural consequence of the fact that, while Scheme has only one lexically scoped language construct (variable bindings), Smalltalk has three lexically scoped language constructs: name bindings (like Scheme), the referent of the return syntax, and the meaning of &amp;quot;self&amp;quot;. The definition of closures above mentioned only &amp;quot;the bindings of free variables&amp;quot;, but that is because the definition was written for the language Scheme, and name (variable) binding is the only lexically scoped construct in Scheme.  Common Lisp also has &amp;quot;return&amp;quot; and &amp;quot;goto&amp;quot;, and these too are captured lexically in a closure. In order to realize the full power of closures, described in Guy Steele's lambda papers, they must capture all lexically scoped language constructs. Generalizing the definition of closure to cover other languages would require using more language-neutral terminology: instead of &amp;quot;bindings of free variables&amp;quot; we would have something like &amp;quot;lexically scoped semantic language constructs.&amp;quot; However, that obscures the origins of the term. &lt;/p&gt;
&lt;p&gt;Fast forward more than 25 years, and we're once again listening to some of the same music we listened to in the late 1970's. We are now considering adding closures to Java, a significantly more complex language than either Scheme or Smalltalk. We're not considering them because they seem like a neat idea, or because they worked out well in other languages, or because we're bored. Rather we're considering them: because of the power and flexibility they will add to the programmer's arsenal; because of the improved readability we expect from programs that use closures instead of the existing alternatives; and because of a number of other recently proposed language extensions that will be unnecessary if closures are added.  In order to get the full power of closures, they should capture all lexically scoped semantic language constructs.  What are the lexically scoped language constructs in Java?&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;The meaning of &lt;em&gt;variable names&lt;/em&gt;.  &lt;/li&gt;
  &lt;li&gt;The meaning of &lt;em&gt;method names&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;The meaning of &lt;em&gt;type names&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;The meaning of &lt;tt&gt;this&lt;/tt&gt;. &lt;/li&gt;
  &lt;li&gt;The meaning of names defined as  statement labels.&lt;/li&gt;
  &lt;li&gt;The referent of an unlabelled &lt;tt&gt;break&lt;/tt&gt; statement. &lt;/li&gt;
  &lt;li&gt;The referent of an unlabelled &lt;tt&gt;continue&lt;/tt&gt; statement. &lt;/li&gt;
  &lt;li&gt;The set of &lt;em&gt;checked exceptions&lt;/em&gt; declared or caught.   &lt;/li&gt;
  &lt;li&gt;The referent of a &lt;tt&gt;return&lt;/tt&gt; statement. &lt;/li&gt;
  &lt;li&gt;The &lt;em&gt;definite assignment&lt;/em&gt; state of variables. &lt;/li&gt;
  &lt;li&gt;The &lt;em&gt;definite &lt;/em&gt;&lt;em&gt;unassignment&lt;/em&gt; state of variables. &lt;/li&gt;
  &lt;li&gt;The &lt;em&gt;reachability state&lt;/em&gt; of the code&lt;sup&gt;3&lt;/sup&gt;. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In addition, Java has one other significant difference from either Scheme or Smalltalk: Java is statically typed. That means that each expression has a type at compile-time. So if we add closures, we need to have some appropriate type for a closure. Since a closure is an anonymous function, it is natural to consider adding function types to the language. But this  is not a mandate. As you can see by the two variations of our closures proposal (the nominal and the functional versions) we believe it is possible to add closures without adding function types with a limited loss of functionality (higher-order programming becomes  impractical). &lt;a href="http://www.javac.info/"&gt;Our proposal for closures&lt;/a&gt; addresses every item on this checklist. There are additional features of our proposal (the control invocation syntax and  the closure conversion) that don't relate directly to the definition of closures, but which make them integrate very nicely with existing language features. And there are additional features not  mentioned in the  spec (such as proper tail recursion) that would be helpful to realize the full potential of closures. &lt;/p&gt;
&lt;p&gt;What about  anonymous inner classes? It turns out that they don't pass muster on any item on this checklist. Let's set aside the fact that  local variables from enclosing scopes must be &lt;tt&gt;final&lt;/tt&gt; to be used inside an anonymous class. The problem is that variable names are simply not resolved in the correct scope. They are resolved in the scope of the anonymous class that you're creating, not the enclosing scope. If you're creating an instance of an interface then it's probably not too much of a problem because most interfaces don't have any (constant) variable definitions. But anonymous inner classes fail every other item on this checklist  as well, most of them fatally. Most &lt;a href="http://crazybob.org/2006/10/java-closure-spectrum.html"&gt;alternative proposals&lt;/a&gt; don't actually address any of the items on this list, and so fail to provide the power of closures any more than  existing language constructs. &lt;/p&gt;
&lt;p&gt;Setting aside all the programming language  theory, don't anonymous inner classes provide, in practice, all of the advantages of closures? &lt;a href="http://www.bejug.org/confluenceBeJUG/display/PARLEYS/Closures+for+Java"&gt;I believe I've already shown&lt;/a&gt; that the answer is no. It is certainly true that for any program you can write using closures, you can write a roughly equivalent program using anonymous inner classes. That's because the Java programming language is &lt;a href="http://en.wikipedia.org/wiki/Turing_completeness"&gt;Turing-complete&lt;/a&gt;. But you will probably find yourself resorting to a significant and awkward refactoring of the code that has nothing to do with the purpose of the code. In fact, you can write a roughly equivalent program using assembly language if you have the stomach for such an effort. On the other hand, true closures increase the power of a language by adding to the kinds of abstractions you can express. &lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;Acknowledgments: my thanks to Gilad Bracha,  John Rose, and Guy Steele for filling me in on and fact-checking the terminology and relevant history. Any remaining historical fantasies are my own. &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;sup&gt;1&lt;/sup&gt; This is Guy Steele's impression of the late 1970's music era [personal communication]. &lt;/p&gt;
&lt;p&gt;&lt;sup&gt;2&lt;/sup&gt; Scheme was the first lexically scoped Lisp, but certainly not the first lexically scoped programming language. Algol60, for example, was lexically scoped. See also Landin's &lt;a href="http://scholar.google.com/scholar?hl=en&amp;amp;lr=&amp;amp;cluster=2856797924573721037"&gt;&lt;em&gt;The Next 700 Programming Languages&lt;/em&gt;&lt;/a&gt;. &lt;/p&gt;
&lt;p&gt;&lt;sup&gt;3&lt;/sup&gt; Arguably part of the lexical semantics or not, reachability state is valuable to capture in practice. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-4321764360411487609?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=4321764360411487609' title='34 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/4321764360411487609'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/4321764360411487609'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/01/definition-of-closures.html' title='A Definition of Closures'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>34</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-3024727992593991191</id><published>2007-01-19T14:46:00.000-08:00</published><updated>2007-01-19T15:10:13.334-08:00</updated><title type='text'>Video Interview at Javapolis</title><content type='html'>&lt;p&gt;Ted Neward interviewed me  at Javapolis last month, and &lt;a href="http://www.bejug.org/confluenceBeJUG/display/PARLEYS/Neal+Gafter+JavaPolis+2006+interview"&gt;the video has just been posted&lt;/a&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Who's your friend? (frog on my shoulder)&lt;/li&gt;
  &lt;li&gt;Who are you and what do you do?&lt;/li&gt;
  &lt;li&gt;What are you presenting at Javapolis?&lt;/li&gt;
  &lt;li&gt;Why are Closures for Java important?&lt;/li&gt;
  &lt;li&gt;What are the differences between the two Closures proposals?&lt;/li&gt;
  &lt;li&gt;What kinds of problems is your proposal trying to solve?&lt;/li&gt;
  &lt;li&gt;Is Java becoming too complex?&lt;/li&gt;
  &lt;li&gt;Did Generics add complexity to the Java language?&lt;/li&gt;
  &lt;li&gt;Can OpenJDK lead to a fragmentation of the Java platform?&lt;/li&gt;
  &lt;li&gt;How does it feel to have your code now splashed out in the open?&lt;/li&gt;
  &lt;li&gt;What should I learn to be able to change the Java compiler? &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;You can jump to any section of the interview, or just &lt;a href="http://www.google.com/"&gt;skip the whole thing&lt;/a&gt;. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-3024727992593991191?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=3024727992593991191' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3024727992593991191'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3024727992593991191'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/01/video-interview-at-javapolis.html' title='Video Interview at Javapolis'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-137785271746925028</id><published>2007-01-16T18:44:00.000-08:00</published><updated>2007-01-16T18:45:25.283-08:00</updated><title type='text'>Primate Parts</title><content type='html'>&lt;p&gt;Recently &lt;a href="http://www.chris-lamb.co.uk/blog/"&gt;Chris Lamb&lt;/a&gt; and friends &lt;a href="http://www.chris-lamb.co.uk/blog/2007/01/13/three-monkeys_at-xing"&gt;wrote about their experience adding a feature to javac&lt;/a&gt;, a pastime slightly more popular than it used to be now that &lt;a href="http://blogs.sun.com/ahe/entry/javac_open_sourced"&gt;javac's sources have been opened under the GPL&lt;/a&gt;. And he found something strange: &lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;&amp;quot;Anyway, it turns out that the javacc [sic] code is messy. Really &lt;em&gt;really&lt;/em&gt; messy. But it&amp;rsquo;s the source of great amusement though, not only from the  scary amount of no-op casts, misleading indenting and undocumented  functions, but the lexical token for the &amp;lsquo;@&amp;lsquo; symbol is &amp;lsquo;MONKEYS_AT&amp;lsquo;. No, we have no idea either.&amp;quot;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I responded with a conditional promise to tell him the story:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;&amp;quot;Actually, the indentation is consistent if you have your tabs set at 8 spaces, where God intended them.&lt;/p&gt;
  &lt;p&gt;&amp;quot;There&amp;rsquo;s a story behind MONKEYS_AT, and if you know it this little  piece of code is a funny inside joke. But if you want me to tell you,  you&amp;rsquo;ll have to take back your assertion that javac&amp;rsquo;s code is messy and  tell me that it&amp;rsquo;s a work of art.&amp;quot;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Chris quickly buckled to the pressure, responding by email:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;&amp;quot;Yes, it is true - when set it to 8 spaces, it seems to look a bit&lt;br /&gt;
    better. What I mean to say is, it's now a work of art and any blemishes&lt;br /&gt;
    are my fault. :)&lt;br /&gt;
    &lt;br /&gt;
    &amp;quot;Anyway, yes, my friends and I would really like to know this story&lt;br /&gt;
    behind the naming of the token though -- we found it at about 3AM whilst&lt;br /&gt;
    hacking on the javac code and it put us off our stride somewhat. ^_^&amp;quot; &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Here's the formerly untold story of MONKEYS_AT.&lt;br /&gt;
  &lt;br /&gt;
During  the development of the JDK5 language features, the Sun team had regular meetings with a team from Denmark that  was designing and implementing the variance feature (since renamed  wildcards, which is a longer and more interesting story).&amp;nbsp; You can find the team member names in &lt;a href="http://portal.acm.org/citation.cfm?coll=GUIDE&amp;amp;dl=GUIDE&amp;amp;id=968162"&gt;the paper describing the work&lt;/a&gt;. The Danish team was led by Mads Torgersen, and we all enjoyed  a number of evenings chatting over beer. During one such session, I was  discussing the work I was doing to implement annotations, and I  mentioned that, unlike the &amp;quot;#&amp;quot; character that seems to have many names,  there don't seem to be any alternative names for the &amp;quot;@&amp;quot; character.  Mads told us that in Denmark, there are a number of names for this  character, including the archaic &amp;quot;monkey's ass&amp;quot;, which refers to the  similarity in appearance of this character to the rear end of a monkey.  We all thought this was hilarious, but perhaps a bit too risque to put in corporate-developed and publicly-visible sources. But it was just too  funny to leave out. Thus I came up with the pun MONKEYS_AT. To this  day that little inside joke in the sources reminds me of the team and  the time we spent together. &lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.gutenberg.org/files/16701/16701-h/16701-h.htm"&gt;&lt;/a&gt;&lt;a href="http://www.gutenberg.org/files/16701/16701-h/16701-h.htm"&gt;&lt;img src="http://www.gafter.com/%7Eneal/p1055.jpg" alt="http://www.gafter.com/~neal/p1055.jpg" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mads, by the way, is the one on the left. ;-)&lt;/p&gt;
&lt;p&gt;There you have it: a disinterested observer, inclined to believe otherwise, comes to appreciate the beauty and humor of javac.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-137785271746925028?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=137785271746925028' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/137785271746925028'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/137785271746925028'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/01/primate-parts.html' title='Primate Parts'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-2226711108596300355</id><published>2007-01-09T09:32:00.000-08:00</published><updated>2007-01-09T09:33:46.072-08:00</updated><title type='text'>MethodNamesInPieces</title><content type='html'>&lt;p&gt;In Smalltalk, the name of a method being invoked is interleaved with the arguments passed to the method. Consequently it is difficult to confuse the order of arguments. In Java, on the other hand, when you invoke a method that accepts three integers it is easy to  get the order wrong. The compiler has no way to detect the problem, so APIs must be carefully designed with the artificial constraint that one should avoid &amp;quot;too many&amp;quot; arguments of &amp;quot;compatible&amp;quot; types. In the context of closures, Smalltalk's syntax  allows &amp;quot;built-in&amp;quot; statement forms such as if-then-else to be expressed as an ordinary method call. When we were putting together the &lt;a href="http://gafter.blogspot.com/2006/08/closures-for-java.html"&gt;original version of the closures proposal&lt;/a&gt; James Gosling suggested this idea to support do-while and if-else style syntax of user-defined control abstraction methods, something that was mentioned in the &lt;em&gt;further ideas&lt;/em&gt; section. We placed this issue on the back burner once we found a nice syntax that works for many of the control-invocation use cases, but a &lt;a href="http://gafter.blogspot.com/2006/12/closures-talk-and-spec-update.html#comment-2545609725456870683"&gt;recently submitted comment&lt;/a&gt; by                               Stefan Schulz                            on my blog reminded me of this issue. His use case is that he'd like to be able to write an API that allows him to refactor this&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;public String toString() {
    StringBuilder sb = new StringBuilder(&amp;quot;[&amp;quot;);
    boolean first = true;
    for (String s : someCollection) {
     if (first) {
            first = false;
        } else {
            sb.append(&amp;quot;, &amp;quot;);
        }
        sb.append(s);
    }
    return sb.append(&amp;quot;]&amp;quot;).toString();
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;into this &lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;public String toString() {
    StringBuilder sb = new StringBuilder(&amp;quot;[&amp;quot;);
    for each(String s : someCollection) {
        sb.append(s);
    } inBetween {
        sb.append(&amp;quot;, &amp;quot;);
    }
    return sb.append(&amp;quot;]&amp;quot;).toString();
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Presumably, the API method would be defined something like this:&lt;/p&gt;
&lt;p&gt;
&lt;blockquote&gt;
&lt;pre&gt;&amp;lt;T&amp;gt; void for &lt;strong&gt;each&lt;/strong&gt;(Iterable&amp;lt;T&amp;gt; it, {T=&amp;gt;void} body) &lt;strong&gt;inBetween&lt;/strong&gt;({=&amp;gt;void} between) {
    boolean first = true;
    for (T t : it) {
     if (first) {
            first = false;
        } else {
            between.invoke();
        }
        body.invoke();
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
  &lt;p&gt;A related advantage of the Smalltalk syntax is that operator overloading comes almost for free. If operator overloading is on the table for JDK7, perhaps we can kill two birds with one stone, by making the name before the first  argument  optional: &lt;/p&gt;
  &lt;blockquote&gt;
    &lt;pre&gt;static BigDecimal (BigDecimal left) plus (BigDecimal right) {
    return left.add(right);
}
static BigDecimal (BigDecimal left) times (BigDecimal right) {
    return left.multiply(right);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;This would allow you to write code like this:&lt;/p&gt;
&lt;blockquote&gt;
&lt;pre&gt;static BigDecimal f(BigDecimal x, BigDecimal y, BigDecimal z) {
    return (x) plus ((y) times (z));
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;It's probably a small step from here to allowing arbitrary symbols as operator names and eliding some parens. I don't think anything is required in the VM, as we can encode these method names using some non-identifier character in the VM signature.  For example, the above methods could be translated in the VM to methods with the names &lt;tt&gt;&amp;quot;each~~inBetween&amp;quot;&lt;/tt&gt;, &lt;tt&gt;&amp;quot;~plus&amp;quot;&lt;/tt&gt;, and &lt;tt&gt;&amp;quot;~times&amp;quot;&lt;/tt&gt; (the number of tilde characters is the number of arguments before &amp;quot;parts&amp;quot; of the name in the method signature).&lt;/p&gt;
&lt;p&gt;There are difficult syntax issues (for example, the each-inBetween example can also be parsed as two separate statements) and I'm not sure I would recommend any of this, but I wanted to share the idea. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-2226711108596300355?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=2226711108596300355' title='15 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2226711108596300355'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/2226711108596300355'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2007/01/methodnamesinpieces.html' title='MethodNamesInPieces'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>15</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-3235073068503710147</id><published>2006-12-18T20:19:00.000-08:00</published><updated>2008-01-31T09:28:42.215-08:00</updated><title type='text'>Closures Talk and Spec Update</title><content type='html'>&lt;span style="font-style:italic;"&gt;This post discusses a draft proposal for adding support for closures to the Java programming language for the Dolphin (JDK 7) release. It was carefully designed to interoperate with the current idiom of one-method interfaces. The latest version of the proposal and a prototype can be found at &lt;a href="http://www.javac.info/"&gt;http://www.javac.info/&lt;/a&gt;.&lt;/span&gt;
&lt;p&gt;My 2006 JavaPolis talk&lt;em&gt; Closures for Java&lt;/em&gt;  has now been published - slides synchronized with a soundtrack - and can be viewed &lt;a href="http://www.bejug.org/confluenceBeJUG/display/PARLEYS/Closures+for+Java"&gt;online at the new Javapolis website, Parleys.com&lt;/a&gt;. If you're still wondering why all the fuss  about closures, I recommend you listen to the talk.&lt;/p&gt;
&lt;p&gt;We've also just published an &lt;a href="http://www.javac.info/closures-v04.html"&gt;update to the specification, version 0.4 &lt;/a&gt;. The specification seems to be setling down quite a bit, as the changes are minor:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;The &lt;span class="Java"&gt;throws&lt;/span&gt; clause of a 
    function type is now placed between the curly braces.&lt;/li&gt;
&lt;li&gt;The description of function 
    types has been  rewritten to emphasize more clearly that function types &lt;em&gt;are interface types&lt;/em&gt; rather than a separate extension to the type system. &lt;/li&gt;
&lt;li&gt;The
    
    closure conversion can now convert a closure that has no result expression to an interface type whose 
    function returns &lt;span class="Java"&gt;java.lang.Void&lt;/span&gt;. This change 
    helps support &lt;em&gt;completion transparency&lt;/em&gt;. A &lt;em&gt;completion transparent&lt;/em&gt; method is one written such that the compiler can infer that an invocation completes normally iff the closure passed to it completes normally. &lt;/li&gt;
  &lt;li&gt;Some examples have been modified to be completion transparent. &lt;/li&gt;
  &lt;li&gt;&lt;span class="Java"&gt;null&lt;/span&gt; is now a subtype of &lt;span class="Java"&gt;Unreachable&lt;/span&gt;, and a number of small related 
    changes. Thanks to R&amp;eacute;mi Forax for pointing out the issues. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I hope the talk, which is  less technical than the specification, makes it easier for you to evaluate the proposal and compare it to the alternatives. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-3235073068503710147?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=3235073068503710147' title='46 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3235073068503710147'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3235073068503710147'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/12/closures-talk-and-spec-update.html' title='Closures Talk and Spec Update'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>46</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-3067423850465703862</id><published>2006-12-15T12:36:00.000-08:00</published><updated>2006-12-15T12:45:12.426-08:00</updated><title type='text'>Javapolis 2006</title><content type='html'>&lt;p&gt;I'm on my way back from Javapolis 2006, unfortunately missing the third 
day of the conference. One of the innovations this year was a bank of ten whiteboards where people brainstormed about the future of the Java language 
and platform. I had a camera with me but I realized too late that I should 
have taken snapshots of the contents of all those boards before I left. I hope 
someone else will. The only snapshots I took were the vote tallies that I 
discuss below. &lt;/p&gt;

&lt;p&gt;There were three issues discussed on those boards that I'd like to share with you.&lt;/p&gt;

&lt;h2&gt;Closures&lt;/h2&gt;

&lt;p&gt;The first board contained a discussion of closures, including an informal 
vote of people &amp;quot;in favor of&amp;quot; and &amp;quot;against&amp;quot; adding support 
for closures. I gave a talk about closures yesterday afternoon, which explained 
the goals and design criteria, showed how they fit quite smoothly into the 
existing language and APIs, and more importantly explained in detail why 
anonymous instance creation expressions do not solve the problems closures 
were designed to solve. Before my talk about closures, the vote was about 55% 
in favor and 45% against. After my talk the vote was 71% in favor and 29% 
against. I don't think any &amp;quot;against&amp;quot; votes were added to the tally 
after my talk. There was also a &lt;em&gt;BOF&lt;/em&gt; (Birds-Of-a-Feather)  session in 
the evening discussing closures. Of the 20 or so attendees none admitted being against 
adding closures. I'm sure the fact that the BOF was scheduled opposite a free 
showing of Casino Royale didn't help, but I had hoped to hear from opponents more about their concerns. We discussed a number of issues and 
concerns, most of which had been discussed on my blog at one time or another. &lt;/p&gt;

&lt;p&gt;One issue that I discussed with a few individuals earlier and then  at 
the BOF was the idea of adding a statement  whose purpose is to yield a 
result  from the surrounding closure, which you could use instead of or 
in addition to providing a result as the last expression in the closure. 
It turns out that adding this feature make closures no longer suitable 
for expressing control abstractions. In other words, &lt;em&gt;adding&lt;/em&gt; 
this feature to the language would  make closures &lt;em&gt;less&lt;/em&gt; 
useful! This is  a very counterintuitive result. I first understood the 
issue by analyzing the  construct using Tennent's Correspondence Principle, but it is much easier for most people to 
understand  when the result is presented as specific examples that fail 
to work as expected. For now I'll leave this as an exercise to the reader, 
but I'll probably write more about it later. Incidentally, I believe the 
folks who designed Groovy got closures wrong for exactly this reason. &lt;/p&gt;

&lt;p&gt;There was a video made of my talk that will be posted to the Javapolis 
website. Ted Neward also interviewed me on video, and Bill Venners 
interviewed me on audio.  As soon as these are available on the web 
I'll blog pointers to them. &lt;/p&gt;

&lt;h2&gt;Native XML Support&lt;/h2&gt;

&lt;p&gt;Mark Reinhold gave a talk on adding native  (i.e. language-level) support 
for XML into Java. Though they were not presented as such, some 
people prefer to think of the proposal as separable into a &lt;em&gt;language 
extension&lt;/em&gt; part and an &lt;em&gt;API&lt;/em&gt; part. The 
proposed APIs appear to be an improvement over the existing alternatives. 
However, the language extension for writing XML literals appears to be only 
marginally more convenient than the XML construction techniques provided by 
&lt;a href="http://www.jdom.org/"&gt;libraries in JDOM&lt;/a&gt;. I personally 
would like to see  the new APIs pursued but  XML creation provided in the 
JDOM way. Mark took a vote by show of hands on how people felt about the two 
issues, but I couldn't see the tally. There was also an informal tally about 
adding native XML support on one of the whiteboards. The result was 29% in 
favor and 71% against. &lt;/p&gt;

&lt;h2&gt;Constructor Invocation for Generics&lt;/h2&gt;

&lt;p&gt;Another much-discussed issue appeared on one of the whiteboards: the 
verbosity of creating instances of generic types. This is typical:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;Map&amp;lt;Pair&amp;lt;String,Integer&amp;gt;,Node&amp;gt; map = new HashMap&amp;lt;Pair&amp;lt;String,Integer&amp;gt;,Node&amp;gt;();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The  problem here is that the type parameters have to be repeated twice. 
One common &amp;quot;workaround&amp;quot; to this problem is to always create your 
generic objects using static factories, but the language should not force 
you to do that. A number of different syntax forms have been suggested for 
fixing this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;var map = new HashMap&amp;lt;Pair&amp;lt;String,Integer&amp;gt;,Node&amp;gt;();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This  unfortuately requires the addition of a new keyword. Another: &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;final map = new HashMap&amp;lt;Pair&amp;lt;String,Integer&amp;gt;,Node&amp;gt;();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This reuses an existing keyword, but at the same time it also makes the 
variable final. Another variation on this idea:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;map := new HashMap&amp;lt;Pair&amp;lt;String,Integer&amp;gt;,Node&amp;gt;();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;In my opinion these three forms all suffer the same flaw: they place the type 
parameters in the wrong place. Since the variable is to be used later in the 
program, the programmer presumably wants  control over its type and the reader wants the type to be clear from the variable declaration.  In this case 
you probably want the variable to be a &lt;code&gt;Map&lt;/code&gt;  and not a 
&lt;code&gt;HashMap&lt;/code&gt;. An idea that addresses my concern is: &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;Map&amp;lt;Pair&amp;lt;String,Integer&amp;gt;,Node&amp;gt; map = new HashMap();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Unfortunately, this is currently legal syntax that creates a &lt;em&gt;raw&lt;/em&gt; 
&lt;code&gt;HashMap&lt;/code&gt;. I don't know if it is possible to change the meaning of 
this construct without breaking backward compatibility. Another possibility: &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;Map&amp;lt;Pair&amp;lt;String,Integer&amp;gt;,Node&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can  see clearly by the presence of the empty angle brackets that the 
type parameters have been omitted where the compiler is asked to infer them. 
Of the alternatives, this is my favorite. I don't think it will be too hard to 
implement in javac using the same techniques that work for static factories of 
generic types. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-3067423850465703862?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=3067423850465703862' title='21 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3067423850465703862'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3067423850465703862'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/12/javapolis-2006.html' title='Javapolis 2006'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>21</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-7433479707202598913</id><published>2006-12-05T14:24:00.000-08:00</published><updated>2006-12-05T14:25:11.257-08:00</updated><title type='text'>Type Literals</title><content type='html'>&lt;p&gt;Yesterday I wrote about &lt;em&gt;&lt;a href="http://gafter.blogspot.com/2006/12/super-type-tokens.html"&gt;super type tokens&lt;/a&gt;&lt;/em&gt;, which is an API that acts like class literals but with two advantages over class literals: they work with generic types, and they provide  full generic type information.  The disadvantages are that they are  more verbose than class literals, and (being a different type than &lt;tt&gt;java.lang.Class&lt;/tt&gt;) they are incompatible with APIs that use type tokens. It turns out that it is possible to get the best of both worlds by adding super type tokens to the language. I would call the resulting construct &lt;em&gt;type literals&lt;/em&gt;. &lt;/p&gt;
&lt;p&gt;The basic idea would be to retrofit &lt;tt&gt;java.lang.reflect.Type&lt;/tt&gt; with generics, in the same way that &lt;tt&gt;java.lang.Class&lt;/tt&gt; was retrofitted with generics in JDK5. Then the type of &lt;tt&gt;List&amp;lt;String&amp;gt;.class&lt;/tt&gt; would be &lt;tt&gt;Type&amp;lt;List&amp;lt;String&amp;gt;&amp;gt;&lt;/tt&gt;, and the structure of the resulting object would contain all of the generic type information that a &lt;tt&gt;Type&lt;/tt&gt; is capable of expressing. The code generated by javac could very well use the trick outlined in my &lt;a href="http://gafter.blogspot.com/2006/12/super-type-tokens.html"&gt;previous blog post&lt;/a&gt;, though I expect there are much more efficient ways of doing it. You would then be able to write&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;
    &lt;pre&gt;Type&amp;lt;List&amp;lt;String&amp;gt;&amp;gt; x = List&amp;lt;String&amp;gt;.class; &lt;/pre&gt;
  &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The &amp;quot;type literal&amp;quot; on the right is currently a syntax error, but this language extension would give meaning to the syntax. How does this fit with the existing meaning of class literals? Very nicely. The type &lt;tt&gt;java.lang.Class&lt;/tt&gt; already extends &lt;tt&gt;java.lang.reflect.Type&lt;/tt&gt;, so a class literal of type &lt;tt&gt;Class&amp;lt;String&amp;gt;&lt;/tt&gt; could be assigned to a variable of type &lt;tt&gt;Type&amp;lt;String&amp;gt;&lt;/tt&gt;. In other words, the following would be legal:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;
    &lt;pre&gt;Type&amp;lt;String&amp;gt; x = String.class;  &lt;/pre&gt;
  &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Adding support for type literals to the language and retrofitting &lt;tt&gt;java.lang.reflect.Type&lt;/tt&gt; would simplify the use of the &lt;a href="http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1512.pdf"&gt;THC pattern&lt;/a&gt; with generic types and make existing type-token-based APIs interoperate nicely with the pattern. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-7433479707202598913?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=7433479707202598913' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/7433479707202598913'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/7433479707202598913'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/12/type-literals.html' title='Type Literals'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-3085325539025155770</id><published>2006-12-04T13:04:00.000-08:00</published><updated>2006-12-04T17:00:05.305-08:00</updated><title type='text'>Super Type Tokens</title><content type='html'>&lt;p&gt;When we added generics to Java in JDK5, I changed the class 
&lt;tt&gt;java.lang.Class&lt;/tt&gt; to become a generic type. For example, 
the type of &lt;tt&gt;String.class&lt;/tt&gt; is now &lt;tt&gt;Class&amp;lt;String&amp;gt;&lt;/tt&gt;. 
&lt;a href="http://bracha.org/Site/Home.html"&gt;Gilad Bracha&lt;/a&gt; coined the term 
&lt;em&gt;&lt;a href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf"&gt;type 
tokens&lt;/a&gt;&lt;/em&gt; for this. My intent was to enable a particular style of 
API, which Joshua Bloch calls   the &lt;a href="http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1512.pdf"&gt;&lt;em&gt;THC&lt;/em&gt;,
or &lt;em&gt;Typesafe Heterogenous Container&lt;/em&gt;&lt;/a&gt; pattern.  For some examples of where 
this is used see the APIs for annotations:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;public &amp;lt;A extends &lt;a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/Annotation.html" 
  title="interface in java.lang.annotation"&gt;Annotation&lt;/a&gt;&amp;gt; A &lt;a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html"&gt;java.lang.Class&lt;/a&gt;.&lt;strong&gt;getAnnotation&lt;/strong&gt;(&lt;a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html" title="class in java.lang"&gt;Class&lt;/a&gt;&amp;lt;A&amp;gt;&amp;nbsp;annotationClass)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;My earliest use of this feature (like my earliest use of all recent Java 
language features) appears in the compiler for the Java programming language (javac), in this case
as a utility called Context, and you can 
&lt;a href="https://openjdk.dev.java.net/source/browse/openjdk/compiler/trunk/src/share/classes/com/sun/tools/javac/util/Context.java?rev=HEAD"&gt;
find the code&lt;/a&gt; in the open source version. It was  a utility that allowed 
the compiler to be written as a bunch of separate classes that all refer to 
each other, and solved the hard problem of getting all the parts created in 
an order such that they can be initialized with references to each other. 
The utility is also used to replace pieces of the compiler, for example to 
make related tools like &lt;a href="http://java.sun.com/j2se/javadoc/"&gt;javadoc&lt;/a&gt; 
and &lt;a href="http://java.sun.com/j2se/1.5.0/docs/guide/apt/index.html"&gt;apt, 
the Annotation Processing Tool&lt;/a&gt;, and for testing. Today I would describe 
the utility as a simple &lt;em&gt;dependency injection&lt;/em&gt; framework, but that 
wasn't a popular buzzword at the time.&lt;/p&gt;

&lt;p&gt;Here is a simple but complete example of an API that uses type tokens 
in the THC pattern, from 
&lt;a href="http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1512.pdf"&gt;Josh's 
2006 JavaOne talk&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;
public class Favorites {
    private Map&amp;lt;Class&amp;lt;?&amp;gt;, Object&amp;gt; favorites =
        new HashMap&amp;lt;Class&amp;lt;?&amp;gt;, Object&amp;gt;();
    public &amp;lt;T&amp;gt; void setFavorite(Class&amp;lt;T&amp;gt; klass, T thing) {
        favorites.put(klass, thing);
    }
    public &amp;lt;T&amp;gt; T getFavorite(Class&amp;lt;T&amp;gt; klass) {
        return klass.cast(favorites.get(klass));
    }
    public static void main(String[] args) {
        Favorites f = new Favorites();
        f.setFavorite(String.class, "Java");
        f.setFavorite(Integer.class, 0xcafebabe);
        String s = f.getFavorite(String.class);
        int i = f.getFavorite(Integer.class);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;A &lt;tt&gt;Favorites&lt;/tt&gt; object acts as a typesafe map from  type tokens to  
instances of the  type. The main program in this snippet adds a favorite &lt;tt&gt;String&lt;/tt&gt; and a favorite &lt;tt&gt;Integer&lt;/tt&gt;, which are later taken out. The interesting thing about this pattern is that a 
single &lt;tt&gt;Favorites&lt;/tt&gt; object can be used to hold things of many (i.e. 
heterogenous) types but in a typesafe way, in contrast to the usual kind of 
map in which the values are all of the same static type (i.e. homogenous). When you get your favorite &lt;tt&gt;String&lt;/tt&gt;, it is of type &lt;tt&gt;String&lt;/tt&gt; and you don't have to cast it. &lt;/p&gt;

&lt;p&gt;There is a limitation to this pattern. 
&lt;a href="http://gafter.blogspot.com/2004/09/puzzling-through-erasure-answer.html"&gt;Erasure&lt;/a&gt; 
rears its ugly head: &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;Favorites:15: illegal start of expression
f.setFavorite(List&amp;lt;String&amp;gt;.class, Collections.emptyList());
                          ^&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can't add your favorite &lt;tt&gt;List&amp;lt;String&amp;gt;&lt;/tt&gt; to a &lt;tt&gt;Favorites&lt;/tt&gt; because you simply can't make a type token for a generic type. This design limitation 
is one that a number of people have been running into lately, most recently 
&lt;a href="http://blogs.tedneward.com/default.aspx#aeb09cffb-9962-461b-b732-c33d36f96170"&gt;Ted 
Neward&lt;/a&gt;. &lt;a href="http://crazybob.org/"&gt;&amp;quot;Crazy&amp;quot; Bob Lee&lt;/a&gt; also 
asked me how to solve a related problem in a dependency injection framework 
he is developing. The short answer is that you can't do it using type tokens.&lt;/p&gt;

&lt;p&gt;On Friday I realized you can solve these problems without using type tokens 
at all, using a library. I wish I had realized this three years ago; perhaps 
there was no need to put support for type tokens directly in the language. I 
call the new idea &lt;em&gt;super type tokens&lt;/em&gt;. In its simplest form it looks like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;public abstract class TypeReference&amp;lt;T&amp;gt; {}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;tt&gt;abstract&lt;/tt&gt; qualifier is intentional.  It forces clients to subclass this 
in order to create a new instance of &lt;tt&gt;TypeReference&lt;/tt&gt;. You make a super type 
token for &lt;tt&gt;List&amp;lt;String&amp;gt;&lt;/tt&gt; like this: &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;TypeReference&amp;lt;List&amp;lt;String&amp;gt;&amp;gt; x = new TypeReference&amp;lt;List&amp;lt;String&amp;gt;&amp;gt;() {};&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Not quite as convenient as writing &lt;tt&gt;List&amp;lt;String&amp;gt;.class&lt;/tt&gt;, but this 
isn't too bad. It turns out that you can use a super type token to do nearly 
everything you can do with a type token, and more. The object that is created on the right-hand-side is an anonymous class, and using reflection you can get its interface type, including generic type parameters. Josh calls this pattern &amp;quot;Gafter's Gadget&amp;quot;. &lt;a href="http://crazybob.org/"&gt;Bob 
  Lee&lt;/a&gt; elaborated on this idea as follows:&lt;/p&gt;
&lt;blockquote&gt;
&lt;pre&gt;import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * References a generic type.
 *
 * @author crazybob@google.com (Bob Lee)
 */
public abstract class TypeReference&amp;lt;T&amp;gt; {

    private final Type type;
    private volatile Constructor&amp;lt;?&amp;gt; constructor;

    protected TypeReference() {
        Type superclass = getClass().getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
    }

    /**
     * Instantiates a new instance of {@code T} using the default, no-arg
     * constructor.
     */
    @SuppressWarnings("unchecked")
    public T newInstance()
            throws NoSuchMethodException, IllegalAccessException,
                   InvocationTargetException, InstantiationException {
        if (constructor == null) {
            Class&amp;lt;?&amp;gt; rawType = type instanceof Class&amp;lt;?&amp;gt;
                ? (Class&amp;lt;?&amp;gt;) type
                : (Class&amp;lt;?&amp;gt;) ((ParameterizedType) type).getRawType();
            constructor = rawType.getConstructor();
        }
        return (T) constructor.newInstance();
    }

    /**
     * Gets the referenced type.
     */
    public Type getType() {
        return this.type;
    }

    public static void main(String[] args) throws Exception {
        List&amp;lt;String&amp;gt; l1 = new TypeReference&amp;lt;ArrayList&amp;lt;String&amp;gt;&amp;gt;() {}.newInstance();
        List l2 = new TypeReference&amp;lt;ArrayList&amp;gt;() {}.newInstance();
    }
}
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This pattern can be used to solve 
&lt;a href="http://blogs.tedneward.com/default.aspx#aeb09cffb-9962-461b-b732-c33d36f96170"&gt;Ted 
Neward's&lt;/a&gt; problem, and most problems where you would otherwise use type tokens but you 
need to support generic types as well as 
&lt;a href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.7"&gt;reifiable&lt;/a&gt; 
types. Although this isn't much more than a &lt;a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6192554"&gt;generic factory interface&lt;/a&gt;, the automatic hook into the rich generic reflection system is more than you can get with simple class literals. With a few more bells and whistles (&lt;tt&gt;toString&lt;/tt&gt;, &lt;tt&gt;hashCode&lt;/tt&gt;, &lt;tt&gt;equals&lt;/tt&gt;, etc) I think this is a worthy candidate for inclusion in the JDK. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-3085325539025155770?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=3085325539025155770' title='18 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3085325539025155770'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3085325539025155770'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/12/super-type-tokens.html' title='Super Type Tokens'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>18</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-7515625649324994183</id><published>2006-11-22T12:17:00.000-08:00</published><updated>2006-11-22T12:19:36.490-08:00</updated><title type='text'>Linear Time Sort Puzzler</title><content type='html'>&lt;p&gt;Interviewing for an engineering position at Google can be grueling and 
humbling. You get less than an hour with each interviewer, and may get one 
technical problem after another to solve. If you have performance anxiety 
you may have a hard time focusing on the problem. The best approach, if 
you can do it, is to think of the interview as a technically challenging 
but friendly brainstorming session. If you get hired, that's what your life will be like.&lt;/p&gt;

&lt;p&gt;My friend, Jim Davis, told me about someone he interviewed earlier this week. 
The candidate thought 
the interview wasn't going well and hoped to impress Jim by
sharing an idea he had: a new algorithm for sorting in linear time. It 
isn't a sort based exclusively on comparisons; it can be proven that any 
such sort must perform O(&lt;em&gt;n&lt;/em&gt; log &lt;em&gt;n&lt;/em&gt;) comparisons. It isn't 
a bucket sort, which is a standard algorithm for this problem (assuming 
certain characteristics of the input set). But the candidate's algorithm 
helped Jim understand the candidate's capabilities. &lt;/p&gt;

&lt;p&gt;The algorithm works  like this: you start by making a linear scan through 
the &lt;em&gt;n&lt;/em&gt; numbers to be sorted and note the largest and smallest of the 
elements. Using that, you compute a linear function &lt;em&gt;f(x)&lt;/em&gt; that will 
map the smallest input element to zero and the largest to &lt;em&gt;n&lt;/em&gt;. Then, 
for each input element &lt;em&gt;x&lt;sub&gt;i&lt;/sub&gt;&lt;/em&gt;, you fork a task that waits 
&lt;em&gt;f(x&lt;sub&gt;i&lt;/sub&gt;)&lt;/em&gt; milliseconds and then outputs 
&lt;em&gt;x&lt;sub&gt;i&lt;/sub&gt;&lt;/em&gt;. After &lt;em&gt;n&lt;/em&gt; milliseconds the output contains 
the input elements in sorted order. &lt;/p&gt;
&lt;p&gt;There may be problems when two tasks attempt to output their data at 
nearly the same time, but let's ignore that for a moment and assume an 
&amp;quot;ideal&amp;quot; system. If you have a truly concurrent computer, this 
may run in O(&lt;em&gt;n&lt;/em&gt;) time using O(&lt;em&gt;n&lt;/em&gt;) processors, thereby 
consuming a total of O(&lt;em&gt;n&lt;sup&gt;2&lt;/sup&gt;&lt;/em&gt;) processing time. There are 
far better concurrent sorting algorithms around.   Much more interesting 
is the idea of running this algorithm on a sequential computer with a 
non-preemptive scheduler. The non-preemptive scheduler avoids the problem 
of two tasks producing data at the same time. The scheduler can also ensure 
that the tasks run in their proper order, even if the running time of some 
tasks causes others to start slightly &amp;quot;too late&amp;quot;. &lt;/p&gt;

&lt;p&gt;Jim explained the 
problem with the algorithm, concluding &amp;quot;so you've reduced the problem 
of sorting in linear time to a different linear time sorting 
algorithm.&amp;quot; After Jim explained this remark, the 
candidate replied &amp;quot;well, the idea isn't really very well thought out.&amp;quot; 
Here is the puzzle: what was Jim talking about?&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-7515625649324994183?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=7515625649324994183' title='16 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/7515625649324994183'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/7515625649324994183'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/11/linear-time-sort-puzzler.html' title='Linear Time Sort Puzzler'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>16</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-3676452317612924752</id><published>2006-11-20T21:04:00.000-08:00</published><updated>2006-11-20T21:07:48.153-08:00</updated><title type='text'>A Thread Pool Puzzler</title><content type='html'>&lt;p&gt;I participated in the design and development of a couple of concurrency 
libraries for shared-memory multiprocessors long before such machines were 
popular. So when I started using &lt;tt&gt;java.util.concurrent&lt;/tt&gt; 
I was already somewhat comfortable with the concepts. But when I used 
it more intensely for production work in the 
&lt;a href="http://www.google.com/calendar/"&gt;Google Calendar&lt;/a&gt; server, 
I ran into a couple of &amp;quot;gotcha&amp;quot; 
situations. I'd like to tell you about one in particular, in part because it might 
help you avoid the problem yourself, and in part because I believe this issue 
exposes some missing functionality in the concurrency framework. &lt;/p&gt;

&lt;p&gt;Many parallel programming problems can be expressed using 
&lt;em&gt;fork-join&lt;/em&gt; parallelism, in which tasks spawn, or &amp;quot;fork&amp;quot;, 
a number of subtasks that can be executed in parallel. The caller then 
waits for these subtasks to complete by &amp;quot;join&amp;quot;ing with them. 
Consider the following sequential program. It is an abstract model of 
some larger program that has three logical layers.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;
class Program {
    static final int N = 3;
    public static void main(String[] args) {
        doSomeWork();
        loopNtimes(N, new Runnable() {
                public void run() { doLayerOne(); }
            });
        System.out.println();
    }

    static void doLayerOne() {
        doSomeWork();
        loopNtimes(N, new Runnable() {
                public void run() { doLayerTwo(); }
            });
    }

    static void doLayerTwo() {
        doSomeWork();
        loopNtimes(N, new Runnable() {
                public void run() { doLayerThree(); }
            });
    }

    static void doLayerThree() {
        doSomeWork();
    }
    static void loopNtimes(int n, Runnable runnable) {
        for (int i=0; i&amp;lt;n; i++) runnable.run();
    }
    static void doSomeWork() {
        System.out.print(".");
        try { Thread.sleep(500L); } catch (InterruptedException _) {}
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;This program prints  40 dots, taking a half second for each one. It runs to 
completion in about 20 seconds. Let's rewrite the loops as concurrent (instead 
of sequential) loops, using an idiom recommended by Martin Buchholz. To do 
that we replace the method loopNtimes with the following: &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;    static ExecutorService threadPool = Executors.newCachedThreadPool();
      static void loopNtimes(int n, Runnable runnable) {
        Collection&amp;lt;Callable&amp;lt;Object&amp;gt;&amp;gt; c = new ArrayList&amp;lt;Callable&amp;lt;Object&amp;gt;&amp;gt;();
        for (int i=0; i&amp;lt;n; i++) c.add(Executors.callable(runnable));
        Collection&amp;lt;Future&amp;lt;Object&amp;gt;&amp;gt; futures = null;
        try { futures = threadPool.invokeAll(c); } catch (InterruptedException _) {}
        if (futures != null) for (Future&amp;lt;Object&amp;gt; f : futures) {
            try { f.get(); }
            catch (InterruptedException ex) {}
            catch (ExecutionException ex) {
                ex.printStackTrace();
                System.exit(1);
            }
        }
    }&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This requires a couple of other minor changes to the program (two import 
statements and &lt;tt&gt;System.exit(0)&lt;/tt&gt; at the end of 
&lt;tt&gt;main&lt;/tt&gt;), but the program now runs in two seconds 
instead of twenty. So far so good, but if &lt;tt&gt;N&lt;/tt&gt; is larger, say a  hundred, 
this program fails. It throws &lt;tt&gt;OutOfMemoryError&lt;/tt&gt; becuase it tries to 
allocate too many threads. My first attempt to fix this replaced 
the thread pool by one containing a fixed number of threads:&lt;/p&gt;

&lt;blockquote&gt;&lt;pre&gt;    static ExecutorService threadPool = Executors.newFixedThreadPool(100);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This version of the program works and runs in 2 seconds. But why 
should we use 100 threads? If we 
imagine that the &lt;tt&gt;Thread.sleep&lt;/tt&gt; statements represent 
computationally intensive parts of the program, it might make more sense to 
have a number of threads approximately the same as the number of physical 
processors. I'm running this on a  machine with an Intel Cetrino 
Duo processor, which acts roughly like 2 processors. Let's be generous, however, 
and make ten threads. So we modify this version of the program by changing 
100 to 10. That won't be as fast as the version with 100 threads, but just 
how fast will it be?&lt;/p&gt;

&lt;p&gt;If you haven't guessed the punch line by now, I'll tell you: with ten 
threads in the  pool the program prints 11 periods and then 
&lt;em&gt;deadlocks&lt;/em&gt;! If you use a debugger to examine the state of the program to figure out 
what's going on, you'll find the main thread waiting for 
&lt;tt&gt;invokeAll&lt;/tt&gt;,  three threads in 
&lt;tt&gt;doLayerOne&lt;/tt&gt; waiting for 
&lt;tt&gt;invokeAll&lt;/tt&gt;,  seven threads in 
&lt;tt&gt;doLayerTwo&lt;/tt&gt; waiting for 
&lt;tt&gt;invokeAll&lt;/tt&gt;, and &lt;em&gt;there are no threads 
left&lt;/em&gt; to do any of the work of calling 
&lt;tt&gt;doLayerThree&lt;/tt&gt;. This is a classic 
&lt;a href="http://www.amazon.com/exec/obidos/ASIN/0321349601/wwwgaftercom-20"&gt;
thread starvation deadlock&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt; If you're just trying
out this program to see what happens, you might be slightly annoyed
and finally give up and hit control-C to quit the Java program,
but when our program (&lt;a href="http://www.google.com/calendar"&gt;Google Calendar&lt;/a&gt;)
encounters this kind of problem our customers get annoyed,
give up, and sign up for a competitor like 
&lt;a href="http://calendar.yahoo.com/"&gt;Yahoo Calendar&lt;/a&gt; 
or &lt;a href="http://30boxes.com/"&gt;30Boxes&lt;/a&gt;.  Hey, don't 
click those links; trust me, you really want 
&lt;a href="http://www.google.com/calendar"&gt;Google Calendar&lt;/a&gt;.
My point is that we can't leave this to chance.&lt;/p&gt;

&lt;p&gt;What can or should we do about this problem?  The first idea is to change
the 10 back into 100, but those numbers are pulled out of thin air.  Without
analyzing the behavior and interaction of all the places where the thread
pool is used,  understanding the dynamic performance of the application 
under real loads, and placing bounds on the number of tasks that will 
be used at each level in the
program's hierarchy, it is difficult or impossible to pick a number that will
always avoid this kind of deadlock. Another idea is to use unbounded 
thread pools, but as we've seen under high load situations those can 
cause an explosion in the number of threads, resulting in the program 
failing by running out of memory. &lt;/p&gt;

&lt;p&gt;What we did to address this issue is avoid the single monolithic thread
pool altogether. Instead, we use a separate thread pool at every level in
the hierarchy. In terms of this example, we would have a thread 
pool for use in &lt;tt&gt;main&lt;/tt&gt;, one for use 
in &lt;tt&gt;doLayerOne&lt;/tt&gt;, and one for use 
in &lt;tt&gt;doLayerTwo&lt;/tt&gt;.
Every subsystem that requires concurrency
gets its own personal thread pool.  
That way every layer that uses concurrency is guaranteed to make progress
when it has work to do, so this kind of deadlock cannot occur.
But there is a cost to this as well: balancing the sizes of these thread
pools is a black art. During operation we have hundreds of
threads, most of which are sitting around doing nothing. Besides being a waste
of resources, the generous surplus of "extra" threads make debugging 
more difficult than it should be. If the system doesn't break down so 
neatly into layers (perhaps because there are recursive loops in the 
call cycle of the subsystems) then even this solution can break down 
and result in thread starvation. &lt;/p&gt;

&lt;p&gt;The situation is not entirely hopeless. In my opinion, this kind of 
thread starvation should never occur because there is &lt;em&gt;always&lt;/em&gt; 
one thread that can contribute processing power toward execution the 
subtasks: the thread that is waiting for the subtasks to complete. 
Here's 
&lt;a href="http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/AbstractExecutorService.java?rev=HEAD&amp;content-type=text/vnd.viewcvs-markup"&gt;
the implementation&lt;/a&gt; of &lt;tt&gt;invokeAll&lt;/tt&gt; as it appears in the JDK: &lt;/p&gt;

&lt;blockquote&gt;
&lt;pre&gt;    public &amp;lt;T&amp;gt; List&amp;lt;Future&amp;lt;T&amp;gt;&amp;gt; invokeAll(Collection&amp;lt;Callable&amp;lt;T&amp;gt;&amp;gt; tasks)
        throws InterruptedException {
        if (tasks == null)
            throw new NullPointerException();
        List&amp;lt;Future&amp;lt;T&amp;gt;&amp;gt; futures = new ArrayList&amp;lt;Future&amp;lt;T&amp;gt;&amp;gt;(tasks.size());
        boolean done = false;
        try {
            for (Callable&amp;lt;T&amp;gt; t : tasks) {
                FutureTask&amp;lt;T&amp;gt; f = new FutureTask&amp;lt;T&amp;gt;(t);
                futures.add(f);
                execute(f);
            }
            for (Future&amp;lt;T&amp;gt; f : futures) {
                if (!f.isDone()) {
                    try { 
                        f.get(); 
                    } catch(CancellationException ignore) {
                    } catch(ExecutionException ignore) {
                    }
                }
            }
            done = true;
            return futures;
        } finally {
            if (!done)
                for (Future&amp;lt;T&amp;gt; f : futures) 
                    f.cancel(true);
        }
    }&lt;/pre&gt;&lt;/blockquote&gt;
 
&lt;p&gt;This code does not use the &lt;em&gt;current&lt;/em&gt; thread to do any 
of the work of invoking the callables. Below is a slightly modified 
version (I've added a  line to the original and refactored 
it to make it a static method that we can put in the program) that 
 uses the current thread to do any work that another thread 
hasn't already started. I've highlighted the newly added code: &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;    public static &amp;lt;T&amp;gt; List&amp;lt;Future&amp;lt;T&amp;gt;&amp;gt; invokeAll(
            ExecutorService threadPool, Collection&amp;lt;Callable&amp;lt;T&amp;gt;&amp;gt; tasks)
        throws InterruptedException {
        if (tasks == null)
            throw new NullPointerException();
        List&amp;lt;Future&amp;lt;T&amp;gt;&amp;gt; futures = new ArrayList&amp;lt;Future&amp;lt;T&amp;gt;&amp;gt;(tasks.size());
        boolean done = false;
        try {
            for (Callable&amp;lt;T&amp;gt; t : tasks) {
                FutureTask&amp;lt;T&amp;gt; f = new FutureTask&amp;lt;T&amp;gt;(t);
                futures.add(f);
                threadPool.execute(f);
            }
            &lt;span style="color: #FF0000;font-weight: bold;"&gt;// force unstarted futures to execute using the current thread
            for (Future&amp;lt;T&amp;gt; f : futures) ((FutureTask)f).run();&lt;/span&gt;
            for (Future&amp;lt;T&amp;gt; f : futures) {
                if (!f.isDone()) {
                    try { 
                        f.get(); 
                    } catch(CancellationException ignore) {
                    } catch(ExecutionException ignore) {
                    }
                }
            }
            done = true;
            return futures;
        } finally {
            if (!done)
                for (Future&amp;lt;T&amp;gt; f : futures) 
                    f.cancel(true);
        }
    }&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Using this version of &lt;tt&gt;invokeAll&lt;/tt&gt;, the program does not 
experience thread starvation. If the thread pool is reduced in size 
to just one thread, the program runs to completion in about 11 seconds, because two 
threads are contributing to doing the work (the main thread and 
the thread from the pool). &lt;/p&gt;

&lt;p&gt;I discussed this issue with Doug Lea, and he warned me that selecting 
tasks for efficient scheduling in a fork-join concurrency framework is not 
trivial; the standard solution is to have a double-ended queue for each 
worker task where it enqueues its subtasks. The worker removes the most 
recently generated task from this queue for itself to process, thereby 
simulating a depth-first execution strategy in the single-thread case. 
When a worker finds itself without any work to do, it  steals work from 
the other end of the queue of another task. That is, it should steal one 
of the least-recently created (course-grained) subtasks. In addition, 
it is beneficial to have a mechanism to avoid the queue altogether for 
the bottom of the call chain. Doug told me that this strategy was pioneered 
by &lt;a href="http://citeseer.ist.psu.edu/frigo98implementation.html"&gt;the 
Cilk work&lt;/a&gt;, but I first learned 
about this strategy 10 years earlier reading 
&lt;a href="http://portal.acm.org/citation.cfm?id=65864.65866"&gt;&lt;em&gt;WorkCrews: An 
Abstraction for Controlling Parallelism&lt;/em&gt; by Mark T. Vandervoorde and Eric 
S. Roberts&lt;/a&gt;. My implementation provides exactly this 
behavior but with a much simpler implementation. The invocation 
of &lt;tt&gt;run&lt;/tt&gt; executes one of the tasks most 
recently generated by the current thread. When a thread has no more 
work to do, it removes work from the queue of the underlying 
&lt;tt&gt;ExecutorService&lt;/tt&gt;, which is a FIFO queue, and so it takes 
the least-recently generated task of all workers. On the other hand, 
because this implementation shares a single queue among all worker 
threads, there may be additional synchronization overhead compared to 
the WorkCrews/Cilk solution. &lt;/p&gt;

&lt;p&gt;It is possible to use the existing concurrency utilities to work 
around the problem, if you don't mind the task scheduling being far 
from optimal. You can do that by setting &lt;tt&gt;CallerRuns&lt;/tt&gt; policy 
on a &lt;tt&gt;ThreadPoolExecutor&lt;/tt&gt;, 
and using a synchronous queue:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;static ThreadPoolExecutor threadPool =
  new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS,
                         new SynchronousQueue&amp;lt;Runnable&amp;gt;());
static {
    threadPool.setRejectedExecutionHandler(
        new ThreadPoolExecutor.CallerRunsPolicy());
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Doug explained to me that the 
&lt;a href="http://gee.cs.oswego.edu/dl/papers/fj.pdf"&gt;earlier public-domain 
version of the concurrency 
utilities had a full implementation of a framework for fork-join 
parallelism&lt;/a&gt;, but  they didn't get included in JDK5: &lt;/p&gt;
&lt;p&gt;
&lt;blockquote&gt;&amp;quot;... The vast majority of such usages are 
    nicest to support as "loop parallelism" utilities. 
    And it is not so much that utilities based on FJ tasks 
    are inconvenient to use that has kept them 
    out, but instead uncertainty about basic APIs until closures 
    are settled. All of the methods for aggregate operations on 
    collections and arrays (applyToAll, map, reduce, 
    mapReduce, findAny, findAll, etc) require function-type 
    arguments (perhaps along with some sort of purity annotation as 
    might be introduced via JSR305) that, depending on how things work 
    out otherwise, would need to be introduced more generally.&amp;quot;&lt;/blockquote&gt;
&lt;/p&gt;
&lt;p&gt;Did you think I would get through an entire blog post without 
mentioning &lt;a href="http://www.javac.info/"&gt;Closures&lt;/a&gt;?&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-3676452317612924752?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=3676452317612924752' title='13 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3676452317612924752'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/3676452317612924752'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/11/thread-pool-puzzler.html' title='A Thread Pool Puzzler'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>13</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-658007273777465170</id><published>2006-11-13T22:50:00.000-08:00</published><updated>2006-11-13T22:53:02.202-08:00</updated><title type='text'>Closures Esoterica: completion transparency</title><content type='html'>&lt;p&gt;The  &lt;a href="http://www.javac.info/"&gt;Closures for Java&lt;/a&gt; draft specifiation 
(currently at v0.3) is the product of a lot of work. Everything in the spec 
has been discussed and scrutinized before being placed into the specification, 
and is there for a reason. From your point of view,  you have seen  snapshots of our 
specification, with very little explanation of why things are the way they are. 
Changes from one revision to another may  seem arbitrary. I am not writing detailed 
notes on the progress and evolution of the specification and its prototype, because 
there is too much to explain and too little time would be left for me to work on 
the specification and prototype. I am, after all, working on this on my own time. 
I suspect few people would care for that level of detail anyway. Much of the work on the 
specification takes place during face-to-face meetings, after which I update the 
specification to reflect our decisions. Some issues get resolved through email 
discussions. We've been keeping an eye on the comments on this blog, various 
message boards, mailing lists, and elsewhere for input, and meeting with  
interested folks, and that has been a very useful part of the process. Thank 
you for your help!&lt;/p&gt;

&lt;p&gt;I'm preparing the next revision of the specification, and we just resolved an  issue by email. Unless you 
know what the issue is, the change in the upcoming version of the specification 
will appear totally arbitrary. Because the issue was resolved by email, I have 
a nice record of the problem and its resolution. Here is an edited excerpt of the the start of our discussion:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;We'd like programmers to be able to define their own control constructs. 
One  thing that would make this easier   would be if programmer-defined  
control constructs act like built-in ones for the purposes of handling  
reachability of statements (and "can complete normally"). That's why we  
added the &lt;em&gt;bottom&lt;/em&gt; type &lt;tt&gt;java.lang.Unreachable&lt;/tt&gt; to the specification. 
But just having that isn't enough. Watch as I try to define a  
&lt;tt&gt;withLock&lt;/tt&gt; method that is &lt;em&gt;completion transparent&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt; First, ignoring reachability, the library writer might define&lt;/p&gt;

&lt;pre style="margin-left: 0.5in;"&gt;&amp;lt;throws E&amp;gt; void withLock(Lock lock, {=&amp;gt;void throws E} block) throws E { ... }&lt;/pre&gt;

&lt;p&gt;this achieves exception transparency, but not completion transparency. 
If the block returns a value, this would work:&lt;/p&gt;

&lt;pre style="margin-left: 0.5in;"&gt;&amp;lt;T, throws E&amp;gt; T withLock(Lock lock, {=&amp;gt;T throws E} block) throws E { ... }&lt;/pre&gt;

&lt;p&gt;this works because a closure that can't complete normally can be converted, 
via the closure conversion, to   &lt;tt&gt;{=&amp;gt;Unreachable}&lt;/tt&gt;. In practice, 
any specific invocation of &lt;tt&gt;withLock&lt;/tt&gt; will either have a block that 
doesn't return anything (i.e. &lt;tt&gt;=&amp;gt;void&lt;/tt&gt;) or can't complete normally 
(i.e. &lt;tt&gt;=&amp;gt;Unreachable&lt;/tt&gt;}.  You might think, therefore, that the library 
writer need only write  these two overloaded methods to achieve completion 
transparency, and  let overload resolution take care of the rest.&lt;/p&gt;

&lt;p&gt;Unfortunately it isn't that simple. With these two methods, an invocation 
of &lt;tt&gt;withLock&lt;/tt&gt;  using a closure that can't complete normally can be an 
invocation of  either of these methods. That's because the closure conversion 
can  convert a closure that results in &lt;tt&gt;Unreachable&lt;/tt&gt; to an interface whose method returns &lt;tt&gt;void&lt;/tt&gt;.  Since both are applicable, the compiler must select the 
most specific.  Neither of these methods is more specific than the other 
(the  closures are unrelated, given our scheme of mapping function types to  
interfaces), so the invocation is ambiguous.&lt;/p&gt;
 
&lt;p&gt; I don't propose that we mess with the specification for "most  specific". 
I'm afraid that would be a disaster, though maybe you can  reassure me that 
it isn't. Instead, I propose that the closure conversion be allowed to convert 
a closure that results in   &lt;tt&gt;void&lt;/tt&gt; to an interface whose method's return type 
is   &lt;tt&gt;java.lang.Void&lt;/tt&gt;. The generated code would naturally return 
a &lt;tt&gt;null&lt;/tt&gt; value. Then the library writer would write only the second version, 
above, and it would work both for the   &lt;tt&gt;void&lt;/tt&gt;-returning case and 
the &lt;tt&gt;Unreachable&lt;/tt&gt;-returning  case. I think being able to write control 
abstractions as a single  method (instead of two overloadings) is a significant 
advantage. Additionally, this API is more flexible because it can be used by  
programmers to pass a value back through from the closure to the  caller.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We discussed this issue and found the proposed resolution our best option. 
The next version of the proposal will include in the closure conversion a 
provision allowing conversion of a closure that returns &lt;tt&gt;void&lt;/tt&gt; to an 
interface type whose method returns &lt;tt&gt;java.lang.Void&lt;/tt&gt;. You can see hints 
in this email thread that the syntax of a function type has changed slightly 
(the &lt;tt&gt;throws&lt;/tt&gt; clause has moved inside the curly braces), and that a function 
type is now specified to be an interface type, rather than having its own 
type rules. The specification is getting simpler, which is definitely a move
in the right direction!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-658007273777465170?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=658007273777465170' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/658007273777465170'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/658007273777465170'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/11/closures-esoterica-completion.html' title='Closures Esoterica: completion transparency'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-5594504437517228574</id><published>2006-11-05T15:22:00.000-08:00</published><updated>2006-11-05T15:23:14.381-08:00</updated><title type='text'>Reified Generics for Java</title><content type='html'>&lt;p&gt;Many people are unsatisfied with the restrictions caused by the way generics are implemented in 
Java. Specifically, they are unhappy that generic type parameters are not &lt;em&gt;reified&lt;/em&gt;: 
they are not available at runtime. Generics are implemented using &lt;em&gt;erasure&lt;/em&gt;, 
in which generic type parameters are simply removed at runtime. That doesn't render generics 
useless,  because you get typechecking at compile-time based on the generic 
type parameters, and also because the compiler inserts casts in the code (so that you don't 
have to) based on the type parameters.&lt;/p&gt;
  
&lt;p&gt;Generics are implemented using erasure as a response to the design requirement that 
they support &lt;em&gt;migration compatibility&lt;/em&gt;: it should be possible to add generic type 
parameters to existing classes without breaking source or binary compatibility with 
existing clients. 
&lt;a href="http://gafter.blogspot.com/2004/09/puzzling-through-erasure-answer.html"&gt;I wrote 
about this two years ago.&lt;/a&gt; Migration compatibility is exploited widely in JDK5; all 
of the collection classes and interfaces use generics, yet existing code using 
collections continues to work. Without migration compatibility, the collection APIs 
could not be retrofitted use generics; we would probably have added a separate, new 
set of collection APIs that use generics. That was the approach used by C# when 
generics were introduced, but Java did not take this approach because of the huge 
amount of pre-existing Java code using collections. &lt;/p&gt;

&lt;p&gt;While solving one set of problems, erasure adds a set of its own problems. For a 
type parameter &lt;tt&gt;T&lt;/tt&gt;, you can't write a class literal &lt;tt&gt;T.class&lt;/tt&gt;. You 
can't use &lt;tt&gt;instanceof&lt;/tt&gt; to test if an object is of type &lt;tt&gt;T&lt;/tt&gt;. And you 
can't create an array of &lt;tt&gt;T&lt;/tt&gt;. But it gets worse. You also can't write class 
literals for generic types like &lt;tt&gt;List&amp;lt;String&amp;gt;.class&lt;/tt&gt;, or test if an 
object is an &lt;tt&gt;instanceof List&amp;lt;String&amp;gt;&lt;/tt&gt;, or create an array 
of &lt;tt&gt;List&amp;lt;String&amp;gt;&lt;/tt&gt;. The implementation 
of generics using erasure also causes Java to 
have &lt;em&gt;unchecked&lt;/em&gt; operations, which are operations that would normally 
check something at runtime but can't do so because not enough information is 
available. For example, a cast to the type &lt;tt&gt;List&amp;lt;String&amp;gt;&lt;/tt&gt; is an 
unchecked cast, because the generated code checks that the object is a 
&lt;tt&gt;List&lt;/tt&gt; but doesn't check whether it is the right kind of list. &lt;/p&gt;

&lt;p&gt;It isn't too late to add reified generics to Java. There are two basic approaches. 
The first uses the language as it exists today but adds the generic 
type information at runtime. In the ideal world, we wait until every 
bit of Java code in the world has been modified to use generics &lt;em&gt;safely&lt;/em&gt;, 
and then go through a transition in which we start recording type parameters at 
runtime by using a new javac and VM. There are two main difficulties with this 
approach. First, it is not 
compatible. It is not source compatible because you would no longer be allowed to 
use raw types (i.e., it is impractical to wait until &lt;em&gt;all&lt;/em&gt; code has been 
generified); it is not binary compatible because new clients would invoke new 
kinds of constructors for generic classes that also record the type parameters, 
but existing classes do not have those constructors. (A hybrid approach
is being investigated in which the system records type parameters 
only when they are available, but I haven't yet seen a workable proposal along 
these lines.) The second problem is more 
insidious: lots of existing code uses generics but uses them in an &lt;em&gt;unsafe&lt;/em&gt; 
way. For example, I have seen code that creates an  &lt;tt&gt;ArrayList&amp;lt;Object&amp;gt;&lt;/tt&gt;, but later casts 
it to a &lt;tt&gt;List&amp;lt;String&amp;gt;&lt;/tt&gt; where the author knows that it only contains objects of type 
&lt;tt&gt;String&lt;/tt&gt;. I would not be surprised to find such code in the JDK. 
Such code must fail at runtime when generics are reified, so some existing 
(but working) code would be broken. &lt;/p&gt;

&lt;p&gt;The other approach modifies the language so that the declaration of a generic parameter 
distinguishes  reified type parameters from erased ones. It is a pure extension of the 
language. The existing syntax for generics would continue to designate 
generics by type erasure, but a newly introduced syntax would be used to declare 
reified type parameters. Perhaps something like this:&lt;/p&gt;

&lt;pre style="margin-left:0.5in"&gt;class NewCollection&amp;lt;&lt;span style="color:#FF3300;font-weight:bold;font-size:larger"&gt;class&lt;/span&gt; E&amp;gt; extends Collection&amp;lt;E&amp;gt; { ... }
class NewList&amp;lt;&lt;span style="color:#FF3300;font-weight:bold;font-size:larger"&gt;class&lt;/span&gt; E&amp;gt; extends NewCollection&amp;lt;E&amp;gt;, List&amp;lt;E&amp;gt; { ... }
&lt;/pre&gt;

&lt;p&gt;The rules for these reified type parameters are  straightforward. When using a 
reified generic class, the type argument has to be a reified type. You would not be 
allowed to create a &lt;tt&gt;NewCollection&lt;/tt&gt; in its raw form. Code that uses only reified 
types would never get an &lt;em&gt;unchecked&lt;/em&gt; warning from the compiler, because 
the compiler can always generate the correct checking code. If you have a reference of 
type &lt;tt&gt;Collection&lt;/tt&gt; that refers to a &lt;tt&gt;NewCollection&amp;lt;String&amp;gt;&lt;/tt&gt;, 
you would get a runtime error if you attempt to put anything other than a 
&lt;tt&gt;String&lt;/tt&gt; into it. In this sense reified collections are like 
&lt;tt&gt;java.util.Collections.checkedCollection&lt;/tt&gt;, only better because the element 
type can itself be generic and the guarantees are stronger. 
You can even create an array 
of &lt;tt&gt;E&lt;/tt&gt; inside an implementation of this type. But there is a disadvantage: the 
strategy requires a new set of reified Collections APIs parallel to the existing 
erasure-based ones. This is why C# introduced new collections APIs when they introduced 
generics. &lt;/p&gt;

&lt;p&gt;As the above declaration illustrates, the new reified collection interfaces could be 
extensions of the existing collection interfaces. Consequently, existing APIs that receive 
old collections can be passed new collections. For example, you could pass a 
&lt;tt&gt;NewCollection&amp;lt;String&amp;gt;&lt;/tt&gt; to an API that is declared to receive a 
&lt;tt&gt;Collection&amp;lt;String&amp;gt;&lt;/tt&gt;. In addition, the new reified collection classes 
(that is, the implementations) could be extensions of the existing collection 
classes. That allows the implementation of the old and new collection classes to 
be shared, and  provides a nice migration path. Existing APIs that return old 
collections can be modified to return new collections. Over time, most libraries 
can be migrated to use the new APIs without breaking backward compatibility 
(though it would break unsafe clients). In 
this way we can have a more gradual migration than would be possible with the first 
approach.&lt;/p&gt;

&lt;p&gt;I don't mean to trivialize the work involved: this  requires a significant 
revision of the VM and language specifications and a significant effort from the teams 
who implement VMs, java compilers (i.e. javac and Hotspot), and the core JDK 
libraries. From the programmer's 
point of view, however, the language change is small and mostly involves 
removing restrictions. &lt;/p&gt;

&lt;p&gt;Approaching the problem this way has a secondary benefit. Because the new reified 
collection interfaces don't exist yet, it is possible for  methods to be added to 
them when they are introduced. Perhaps sorting methods belong in &lt;tt&gt;NewList&lt;/tt&gt;? 
If reified generics are added at the same time as 
(or after) closures, a number of useful methods could be added to take advantage of 
closures. Filters, mappers, reducers, and visitors are just some of the ideas.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-5594504437517228574?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=5594504437517228574' title='55 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/5594504437517228574'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/5594504437517228574'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/11/reified-generics-for-java.html' title='Reified Generics for Java'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>55</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-4088507463105488790</id><published>2006-10-22T08:58:00.000-07:00</published><updated>2008-01-31T09:28:09.315-08:00</updated><title type='text'>Closures for Java (v0.3)</title><content type='html'>&lt;span style="font-style:italic;"&gt;This post discusses a draft proposal for adding support for closures to the Java programming language for the Dolphin (JDK 7) release. It was carefully designed to interoperate with the current idiom of one-method interfaces. The latest version of the proposal and a prototype can be found at &lt;a href="http://www.javac.info/"&gt;http://www.javac.info/&lt;/a&gt;.&lt;/span&gt;
&lt;p&gt;We've just completed a major revision and simplification of the Closures for Java specification. Rather than post the specification on this blog, it is &lt;a href="http://www.javac.info/closures-v03.html"&gt;on its own web page, here&lt;/a&gt;. There are two versions of the specification: one with function types and one without. There is a pulldown menu at the top of the specification that makes it display only the text relevant to the version of the specification you want to see. Keeping the specification in this form will allow us to more easily maintain the two parallel specifications so we can compare  them and delay a decision on this issue until later. These specifications are the starting point for our prototype. &lt;/p&gt;
&lt;p&gt;There are two significant changes in this revision. First, there is a completely new syntax for closures and function types. Using the new syntax, with functon types, you can write&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;{int,int =&amp;gt; int} plus = {int x, int y =&amp;gt; x+y};&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;As you can see, we're proposing to add the new &amp;quot;arrow&amp;quot; token =&amp;gt; to the syntax. Just to be perfectly clear, this code declares a variable of function type &lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;{int,int =&amp;gt; int}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;which is a function that takes two ints and yields an int. The variable is named &amp;quot;plus&amp;quot; and it is assigned the closure value &lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre&gt;{int x, int y =&amp;gt; x+y}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;which is a closure that receives two ints (named x and y) and yields their sum.  &lt;/p&gt;
&lt;p&gt;The second major change has to do with the treatment of &amp;quot;restricted&amp;quot; closures. We've done away with the &amp;quot;synchronized&amp;quot; parameters from the previous revision of the specification. Instead, you can inherit from a marker interface to restrict the closure conversion. If you don't use the marker interface, then closures are not restricted when converted to that type. &lt;/p&gt;
&lt;p&gt;Another important change is to the meaning of a function type. It is now defined to be a system-provided interface type, and it is provided in a way that  gives the required subtype relations among function types. That means that in order to invoke a value of function type, instead of simply placing arguments in parens after the function value, you use its &amp;quot;invoke&amp;quot; method. This significantly simplifies the name lookup rules for variables of function type. In fact, now there are no special rules at all. &lt;/p&gt;
&lt;p&gt;As always, your feedback and ideas are welcome. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-4088507463105488790?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=4088507463105488790' title='20 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/4088507463105488790'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/4088507463105488790'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/10/closures-for-java-v03.html' title='Closures for Java (v0.3)'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>20</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-116076072063501958</id><published>2006-10-13T10:31:00.000-07:00</published><updated>2006-10-31T19:42:06.143-08:00</updated><title type='text'>Concurrent Loops Using Java Closures</title><content type='html'>The &lt;span style="FONT-FAMILY:Courier New"&gt;java.util.concurrent&lt;/span&gt; package has very nice support for writing concurrent loops. I used it recently to improve the performance of some code in the &lt;a href="http://www.google.com/calendar" target="blank_" title="Google Calendar"&gt;Google Calendar&lt;/a&gt; Server. In the Calendar Server, we have a class representing an event on a calendar. The following method on an event computed the set of attendees to the event. The old code looked something like this:&lt;br/&gt; &lt;br/&gt; &lt;div style="MARGIN-LEFT:40px"&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;public Collection&amp;lt;Principal&amp;gt; getAttendees() {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; List&amp;lt;Principal&amp;gt; result = new ArrayList&amp;lt;Principal&amp;gt;();&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (EventResponse r : getResponses()) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;if (r.mayAttend()) {&lt;br/&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;result.add(r.getAttendee());&lt;br/&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return result;&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;}&lt;/span&gt;&lt;br/&gt; &lt;/div&gt; &lt;br/&gt; The problem with this code, it turned out, was that &lt;span style="FONT-FAMILY:Courier New"&gt;getAttendee()&lt;/span&gt; has to talk to a remote server to look up the &lt;span style="FONT-FAMILY:Courier New"&gt;Principal&lt;/span&gt; in a database, and although the remote server is very fast, it is far enough away that there is some latency. Since this loop is sequential, when there are many responses it spends most of its time waiting for a response from the remote server, over and over again. Consequently the call to &lt;span style="FONT-FAMILY:Courier New"&gt;getAttendees()&lt;/span&gt; was very slow for events with many attendees. One solution to this kind of problem would be to send a single batch request, and that is probably the best long-term solution to the problem, but the server in this case doesn't yet know how to handle batch requests. So our fix to the immediate performance problem was to use &lt;span style="FONT-FAMILY:Courier New"&gt;java.util.concurrent&lt;/span&gt; and make the requests in parallel; this did speed things up significantly:&lt;br/&gt; &lt;br/&gt; &lt;div style="MARGIN-LEFT:40px"&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;public Collection&amp;lt;Principal&amp;gt; getAttendees() {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; final List&amp;lt;Principal&amp;gt; result = new ArrayList&amp;lt;Principal&amp;gt;();&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; CompletionService&amp;lt;Void&amp;gt; ecs =&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; new ExecutorCompletionService&amp;lt;Void&amp;gt;(threadPool);&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (final EventResponse r : getResponses()) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ecs.submit(new Callable&amp;lt;Void&amp;gt;() {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public Void call() {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (r.mayAttend()) {&lt;br/&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try {&lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Principal attendee = r.getAttendee();&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; synchronized (result) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; result.add(attendee);&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; } catch (Throwable ex) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; LOGGER.log(Level.SEVERE, "Uncaught Exception", ex);&lt;br/&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;/span&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // wait for the tasks to complete&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (final EventResponse r : getResponses()) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; /*discard*/ ecs.take().get();&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } catch (InterruptedException ex) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; throw new AssertionError(ex); // shouldn't happen&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } catch (ExecutionException ex) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; LOGGER.log(Level.SEVERE, "Uncaught Exception", ex);&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return result;&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;}&lt;/span&gt;&lt;br/&gt; &lt;/div&gt; &lt;br/&gt; When I find code like this I have a few reactions. First, my eyes glaze over at the complexity. Then, if I'm interested, I look carefully at the code to try to understand it. After all, I'm likely to want to do something like this again someday. Finally, I bookmark it so I can add it to my bag of tricks.&lt;br/&gt; I don't think writing a concurrent loop should have to be so complex. Here is what I would like to have written:&lt;br/&gt; &lt;br/&gt; &lt;div style="MARGIN-LEFT:40px"&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;public Collection&amp;lt;Principal&amp;gt; getAttendees() {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; List&amp;lt;Principal&amp;gt; result = new ArrayList&amp;lt;Principal&amp;gt;();&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for eachConcurrently(EventResponse r : getResponses(), threadPool) {&lt;br/&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (r.mayAttend()) {&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;/span&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Principal attendee = r.getAttendee();&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; synchronized (result) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; result.add(attendee);&lt;br/&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;/span&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return result;&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt; &lt;span style="FONT-FAMILY:Courier New"&gt;}&lt;/span&gt;&lt;br/&gt; &lt;/div&gt; &lt;br/&gt; You might think that in order to do this kind of thing we would need to add a concurrent looping statement to the language. Actually, it is possible to add the concurrent looping construct as a library method if you have closures in the language! It isn't trivial to write, but that's why we have people like Doug Lea in the world. An API like this "&lt;span style="FONT-FAMILY:Courier New"&gt;for eachConcurrently&lt;/span&gt;" thing should be written once by an expert and placed into the JDK for everyone to use.&lt;br/&gt; &lt;br/&gt; What should happen if you use &lt;span style="FONT-FAMILY:Courier New"&gt;continue&lt;/span&gt;, &lt;span style="FONT-FAMILY:Courier New"&gt;break&lt;/span&gt;, or &lt;span style="FONT-FAMILY:Courier New"&gt;return&lt;/span&gt; within the body of this loop, or &lt;span style="FONT-FAMILY:Courier New"&gt;throw&lt;/span&gt; an exception? The &lt;span style="FONT-FAMILY:Courier New"&gt;continue&lt;/span&gt; case is easy: it just completes execution of that one iteration, and the other iterations proceed on their merry way. The semantics of &lt;span style="FONT-FAMILY:Courier New"&gt;break&lt;/span&gt; are a bit subtle, but obvious once you realize this is supposed to act like a loop: it completes the current iteration and cancels any other iterations that have not completed, and control returns to the caller of &lt;span style="FONT-FAMILY:Courier New"&gt;for eachConcurrently&lt;/span&gt;. Handling a &lt;span style="FONT-FAMILY:Courier New"&gt;return&lt;/span&gt; statement is similar: it cancels any uncompleted iterations and returns from the enclosing method, which in this case would be &lt;span style="FONT-FAMILY:Courier New"&gt;getAttendees&lt;/span&gt;. Finally, any exception that propagates out of a loop iteration cancels uncompleted iterations and propagates from the loop.&lt;br/&gt; &lt;br/&gt; p.s.: Martin Buchholz offered the follow improved version of the code using &lt;span style="FONT-FAMILY:Courier New"&gt;java.util.concurrent&lt;/span&gt;:&lt;br/&gt; &lt;br/&gt; &lt;div style="MARGIN-LEFT:40px"&gt;  &lt;span style="FONT-FAMILY:Courier New"&gt; public Collection&amp;lt;Principal&amp;gt; getAttendees() {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; final Collection&amp;lt;Principal&amp;gt; result&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; = new ConcurrentLinkedQueue&amp;lt;Principal&amp;gt;();&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  &lt;div style="direction:ltr"&gt;
  &lt;p&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; final Collection&amp;lt;Callable&amp;lt;Object&amp;gt;&amp;gt; tasks&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
      &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; = new ArrayList&amp;lt;Callable&amp;lt;Object&amp;gt;&amp;gt;();&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
      &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; for (final EventResponse r : getResponses())&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
    &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; tasks.add(Executors.callable(new Runnable() { public void run() {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
    &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; try {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
    &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; if (r.mayAttend())&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
    &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; result.add(r.getAttendee());&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
    &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; } catch (Throwable ex) {&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
    &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; LOGGER.log(Level.SEVERE, "Uncaught Exception", ex);&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
    &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; }}}));&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
      &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; try {&lt;br style="FONT-FAMILY:Courier New"/&gt;
      &lt;/span&gt;&lt;span style="FONT-FAMILY:Courier New"&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; threadpool.invokeAll(tasks);&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
      &lt;span style="FONT-FAMILY:Courier New"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; } catch (InterruptedException ex) {}&lt;br style="FONT-FAMILY:Courier New"/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; return new ArrayList&amp;lt;Principal&amp;gt;(result);&lt;/span&gt;&lt;br style="FONT-FAMILY:Courier New"/&gt;  
      &lt;span style="FONT-FAMILY:Courier New"&gt; &lt;/span&gt; }&lt;br/&gt;  
  &lt;/p&gt;
  &lt;/div&gt; &lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-116076072063501958?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=116076072063501958' title='20 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/116076072063501958'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/116076072063501958'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/10/concurrent-loops-using-java-closures.html' title='Concurrent Loops Using Java Closures'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>20</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115985043889128988</id><published>2006-10-02T21:39:00.000-07:00</published><updated>2007-08-02T17:58:19.648-07:00</updated><title type='text'>Iterative control abstraction: user-defined loops</title><content type='html'>A couple of people have written about using Java closures to write methods that act as looping constructs. For example, iterating through a map is currently an ugly exercise in boilerplate:&lt;br/&gt; &lt;br/&gt; &lt;div style="MARGIN-LEFT: 40px"&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt;Droid seekDroid(Map&amp;lt;String,Droid&amp;gt; map) {&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: #cc0000"&gt;for (Map.Entry&amp;lt;String,Droid&amp;gt; entry : map.entrySet()) {&lt;/span&gt;&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace; COLOR: #cc0000"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace; COLOR: #cc0000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; String droidName = entry.getKey();&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace; COLOR: #cc0000"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace; COLOR: #cc0000"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Droid droid = entry.getValue();&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (droid.isSought()) {&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.printf("'%s' is the droid we seek.%n", droidName);&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return droid;&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt;}&lt;/span&gt;&lt;br/&gt; &lt;/div&gt; &lt;br/&gt; It has been proposed that we add looping methods to &lt;span style="FONT-FAMILY: courier new,monospace"&gt; Collection&lt;/span&gt; and &lt;span style="FONT-FAMILY: courier new,monospace"&gt;Map&lt;/span&gt; that take advantage of closures, but it would be incompatible to add methods to an existing interface. We can accomplish the same thing using static methods. With one small additional twist to the closures proposal, we could make it even easier to write a method that iterates over maps. Here is what we want our client to look like:&lt;br/&gt; &lt;br/&gt; &lt;div style="MARGIN-LEFT: 40px"&gt; &lt;span style="FONT-FAMILY: Courier New"&gt;import static &lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;java.util.Collections.eachEntry;&lt;/span&gt;&lt;br/&gt; ...&lt;br/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&lt;/span&gt;&lt;span style="FONT-FAMILY: courier new,monospace"&gt;Droid seekDroid(Map&amp;lt;String,Droid&amp;gt; map) { &lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace; COLOR: #009900"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="FONT-WEIGHT: bold"&gt;for&lt;/span&gt; eachEntry(String droidName, Droid droid : map) {&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (droid.isSought()) {&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.printf("'%s' is the droid we seek.%n", droidName);&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return droid;&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt; }&lt;/span&gt;&lt;br/&gt; &lt;/div&gt; &lt;br/&gt; To enable this, the following would be added to &lt;span style="FONT-FAMILY: Courier New"&gt;java.util.Collections&lt;/span&gt;:&lt;br/&gt; &lt;br/&gt; &lt;div style="MARGIN-LEFT: 40px"&gt;  &lt;span style="FONT-FAMILY: courier new,monospace"&gt;public interface Block2&amp;lt;K,V,throws E&amp;gt; {&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt;  &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; void invoke(K k, V v) throws E;&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt;  &lt;span style="FONT-FAMILY: courier new,monospace"&gt;}&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt;  &lt;span style="FONT-FAMILY: courier new,monospace"&gt;public static &amp;lt;K,V,throws E&amp;gt;&lt;br/&gt;  void &lt;span style="COLOR: #009900; FONT-WEIGHT: bold"&gt;for&lt;/span&gt;  eachEntry(Map&amp;lt;K,V&amp;gt; map, Block2&amp;lt;K,V,E&amp;gt; block) throws E { &lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt;  &lt;span style="FONT-FAMILY: courier new,monospace"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; for (Map.Entry&amp;lt;K,V&amp;gt; entry : map.entrySet()) {&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt;  &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; block.invoke(entry.getKey(), entry.getValue());&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt;  &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br style="FONT-FAMILY: courier new,monospace"/&gt;  &lt;span style="FONT-FAMILY: courier new,monospace"&gt;}&lt;/span&gt;&lt;br/&gt; &lt;/div&gt; &lt;span style="FONT-FAMILY: courier new,monospace"&gt;&lt;/span&gt;&lt;br/&gt; Notice &lt;a&gt;&lt;/a&gt;the "&lt;span style="FONT-FAMILY: courier new,monospace"&gt;for&lt;/span&gt;" qualifier on the declaration of &lt;span style="FONT-FAMILY: courier new,monospace"&gt;eachEntry&lt;/span&gt;, and the &lt;span style="FONT-FAMILY: courier new,monospace"&gt; for&lt;/span&gt; keyword on its invocation. Methods defined this way and then invoked using the control abstraction syntax would require the use of the &lt;span style="FONT-FAMILY: courier new,monospace"&gt;for&lt;/span&gt; keyword on the invocation. The compiler arranges such control abstractions to act like loops, by properly interpreting &lt;span style="FONT-FAMILY: courier new,monospace"&gt;break&lt;/span&gt; and &lt;span style="FONT-FAMILY: courier new,monospace"&gt;continue&lt;/span&gt; statements within the body of the closure. Although this example doesn't use &lt;span style="FONT-FAMILY: courier new,monospace"&gt;break&lt;/span&gt; or &lt;span style="FONT-FAMILY: courier new,monospace"&gt;continue&lt;/span&gt; statements, the mere presence of the &lt;span style="FONT-FAMILY: courier new,monospace"&gt; for&lt;/span&gt; keyword on the invocation helps the reader understand the code. In this way user-defined control constructs could be written that appear and act as loops.&lt;br/&gt; &lt;br/&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115985043889128988?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115985043889128988' title='27 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115985043889128988'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115985043889128988'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/10/iterative-control-abstraction-user.html' title='Iterative control abstraction: user-defined loops'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>27</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115850029098253266</id><published>2006-09-17T06:37:00.000-07:00</published><updated>2006-10-13T10:42:11.356-07:00</updated><title type='text'>Failure of Imagination in Language Design</title><content type='html'>&lt;p&gt;Failure of imagination - that is, failure to make language constructs
orthogonal because you aren't quite sure how people will need to use them
together - is one of the most common and severe errors you can make in programming
language design. It is an error that is often impossible to correct after
the fact. There is an approach to programming language design that you can
take to maximize your opportunities to err in this way: consider the
interactions of individual language features and decide on a case-by-case
basis if the interaction will be allowed or not (or even what the semantics
should be) based on whether or not you can find use cases and which
semantics best fit those use cases.

&lt;p&gt;This is an approach favored by expert API designers, because the domain of
API design is best suited to this approach and these designers expect their
expertise to carry from one domain to the other. In an API, the components
of the API fit together in particular and well-defined patterns due to the
typing and subtyping relationships between the elements; the job of the API
designer is to ensure that the patterns you can build with the API elements
satisfy a set of use cases.

&lt;p&gt;In a programming language, on the other hand, the elements that are used to
assemble programs are ideally orthogonal and independent. Programmers can
assemble the elements in arbitrary ways, often unexpected but surprisingly
useful ways. The "patterns" movement for example records some of these ideas
by creating a common terminology for newly discovered ways of assembling
programs from primitives. 

&lt;p&gt;To be sure, use cases also play a very important role in language
design, but that role is a completely different one than the kind of role
that they play in API design. In API design, satisfying the requirements of the use cases is a &lt;em&gt;sufficient&lt;/em&gt; condition for completeness. In language design, it is a &lt;em&gt;necessary&lt;/em&gt; condition.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115850029098253266?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115850029098253266' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115850029098253266'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115850029098253266'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/09/failure-of-imagination-in-language_17.html' title='Failure of Imagination in Language Design'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115821034131743710</id><published>2006-09-13T21:33:00.000-07:00</published><updated>2008-01-31T09:27:15.404-08:00</updated><title type='text'>Nominal Closures for Java (version 0.2)</title><content type='html'>&lt;span style="font-style:italic;"&gt;This post describes a draft proposal for adding support for closures to the Java programming language for the Dolphin (JDK 7) release. It was carefully designed to interoperate with the current idiom of one-method interfaces. The latest version of the proposal and a prototype can be found at &lt;a href="http://www.javac.info/"&gt;http://www.javac.info/&lt;/a&gt;.&lt;/span&gt;
&lt;p&gt; &lt;em&gt;This revision of the closures proposal eliminates function types, introduces the Unreachable type, and gives related reachability rules. A closure's "return" type is now called its result type. The abbreviated invocation syntax now takes any statement, not just a block, to make nesting work nicely.&lt;/em&gt; &lt;/p&gt; &lt;p style="TEXT-ALIGN: right"&gt; &lt;em&gt;Gilad Bracha, Neal Gafter, James Gosling, Peter von der Ahé&lt;/em&gt; &lt;/p&gt; &lt;p&gt; Modern programming languages provide a mixture of primitives for composing programs. C#, Javascript, Ruby, Scala, and Smalltalk (to name just a few) have direct language support for delayed-execution blocks of code, called &lt;em&gt;closures&lt;/em&gt;. A proposal for closures is working its way through the C++ standards committees as well. Closures provide a natural way to express some kinds of abstraction that are currently quite awkward to express in Java. For programming in the small, closures allow one to abstract an algorithm over a piece of code; that is, they allow one to more easily extract the common parts of two almost-identical pieces of code. For programming in the large, closures support APIs that express an algorithm abstracted over some computational aspect of the algorithm. This proposal outlines a specification of closures for Java without introducing function types. &lt;/p&gt; &lt;h2&gt; 1. Closure Literals &lt;/h2&gt; &lt;p&gt; We introduce a syntactic form for constructing a closure value: &lt;/p&gt; &lt;blockquote&gt; &lt;dl&gt; &lt;dt&gt;&lt;em&gt;Expression3&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Closure&lt;/em&gt;&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;Closure&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;FormalParameters&lt;/em&gt; { &lt;em&gt;BlockStatements&lt;sub&gt;opt&lt;/sub&gt;&lt;/em&gt; &lt;em&gt;Expression&lt;sub&gt;opt&lt;/sub&gt;&lt;/em&gt; }&lt;/dd&gt; &lt;/dl&gt; &lt;/blockquote&gt; &lt;h3&gt; Example &lt;/h3&gt; &lt;p&gt; We can write a closure that adds two to its argument like this: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;interface IntFunction {&lt;br/&gt; int invoke(int i);&lt;br/&gt;}&lt;br/&gt;IntFunction plus2 = (int x){ x+2 };&lt;/pre&gt; &lt;/blockquote&gt; &lt;h2&gt; 2. The type of a closure &lt;/h2&gt; &lt;p&gt; A closure literal has a "closure type" that exists transiently at compile time. It is converted to some object type at compile-time; See &lt;span style="FONT-STYLE: italic"&gt;Closure Conversion&lt;/span&gt; for details. It is a compile-time error if a closure is not subject to a closure conversion. &lt;/p&gt; &lt;p&gt; The type of a closure is inferred from its form as follows: &lt;/p&gt; &lt;p&gt; The argument types of a closure are the types of the declared arguments. &lt;/p&gt; &lt;p&gt; If the body of the closure ends with an expression, the result type of the closure is the type of that expression; otherwise if the closure can complete normally, the result type is &lt;code&gt;void&lt;/code&gt;; otherwise the result type is &lt;code&gt;Unreachable&lt;/code&gt;. &lt;/p&gt; &lt;p&gt; The set of thrown types of a closure are those checked exception types thrown by the body.&lt;br/&gt; &lt;/p&gt; &lt;h3&gt; Example &lt;/h3&gt; &lt;p&gt; The following illustrates a closure being assigned to a variable of a compatible object type.&lt;br/&gt; &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;interface VoidIntBlock&amp;lt;throws E&amp;gt; {&lt;br/&gt; void invoke(int i) throws E;&lt;br/&gt;}&lt;br/&gt;VoidIntBlock&amp;lt;InterruptedException&amp;gt; sleeper = (int t) { Thread.sleep(t); };&lt;/pre&gt; &lt;/blockquote&gt; &lt;h2&gt; 3. &lt;code&gt;synchronized&lt;/code&gt; parameters &lt;/h2&gt; &lt;p&gt; We allow the qualifier &lt;tt&gt;synchronized&lt;/tt&gt; &lt;a&gt;&lt;/a&gt;to be used on formal method arguments. When a closure is passed to such a parameter, the closure conversion (see&lt;em&gt; Closure Conversion&lt;/em&gt;) is allowed to close over its context: the closure may use non-final local variables from enclosing scopes, and may use control-transfer statements such as &lt;tt&gt;break&lt;/tt&gt;, &lt;tt&gt;continue&lt;/tt&gt;, and &lt;tt&gt;return&lt;/tt&gt; that transfer control outside of the body of the closure. An overriding method declaration may only add (i.e. may not remove) the &lt;tt&gt;synchronized&lt;/tt&gt; qualfier to formal parameters compared to a method it overrides; an abstract method that overrides one whose parameter is declared &lt;tt&gt;synchronized&lt;/tt&gt; must itself declare the parameter &lt;tt&gt;synchronized&lt;/tt&gt;. If a closure is passed to a parameter that is not declared &lt;tt&gt;synchronized&lt;/tt&gt;, then the only local variables from enclosing scopes it may access are those that are marked &lt;tt&gt;final&lt;/tt&gt;. &lt;/p&gt; &lt;blockquote&gt; Note: this qualifier is necessary to enable API writers to distinguish &lt;em&gt;synchronous &lt;/em&gt;from &lt;em&gt;asynchronous&lt;/em&gt; receivers of closures. For compatibility with existing APIs, most of which are asynchronous, the default is not allowing closing over the context. The constraint on overriders preserves the substitutability of subtypes: if a closure is allowed when passed to the superclass method, it must be allowed when passed to the subclass method. A consequence of the overriding constraint is that no existing overridable method can be retrofitted to accept synchronous closures without breaking source compatibility. Static methods such as &lt;tt&gt;AccessController.doPrivileged&lt;/tt&gt; can be retrofitted. The &lt;tt&gt;synchronized&lt;/tt&gt; keyword isn't an ideal choice, but it is the best we've found so far. &lt;/blockquote&gt; &lt;p&gt;  Names that are in scope where a closure is defined may be referenced within the closure. It is a compile-time error to access a local variable declared outside the closure from within a closure unless the closure is passed to a parameter that is declared &lt;tt&gt;synchronized&lt;/tt&gt; or the variable was declared final.&lt;br/&gt; &lt;/p&gt; &lt;blockquote&gt; Note: a local variable that is referenced within a closure is in scope in the body of the closure. Consequently the lifetime of objects referenced by such variables may extend beyond the time that the block containing the local declaration completes. &lt;/blockquote&gt; &lt;h2&gt;  4. Closure conversion &lt;/h2&gt; &lt;p&gt;  A closure literal may be assigned to a variable or parameter of any compatible object type by the &lt;span style="FONT-STYLE: italic"&gt;closure conversion&lt;/span&gt;: &lt;/p&gt; &lt;p&gt;  There is a &lt;em&gt;closure conversion&lt;/em&gt; from every closure of type T to every interface type that has a single method &lt;span style="FONT-STYLE: italic"&gt;m&lt;/span&gt; with signature U such that T is &lt;span style="FONT-STYLE: italic"&gt;compatible with &lt;/span&gt;U. A closure of type &lt;em&gt;T&lt;/em&gt; is &lt;span style="FONT-STYLE: italic"&gt;compatible with&lt;/span&gt; a method &lt;em&gt;U&lt;/em&gt; iff all of the following hold: &lt;/p&gt; &lt;ul&gt;  &lt;li&gt;  Either &lt;ul&gt;  &lt;li&gt;  The result type of &lt;em&gt;T&lt;/em&gt; is either the same as the return type of &lt;em&gt;U&lt;/em&gt; or&lt;/li&gt;  &lt;li&gt;  There is an assignment conversion from the result type of &lt;em&gt;T&lt;/em&gt; to the return type of &lt;em&gt;U&lt;/em&gt;; or&lt;/li&gt;  &lt;li&gt;  the result type of &lt;em&gt;T&lt;/em&gt; is &lt;code&gt;Unreachable&lt;/code&gt;.&lt;br/&gt;&lt;/li&gt;  &lt;/ul&gt;&lt;/li&gt;  &lt;li&gt;  &lt;em&gt;T&lt;/em&gt; and &lt;em&gt;U&lt;/em&gt; have the same number of arguments.&lt;/li&gt;  &lt;li&gt;  For each corresponding argument position in the argument list of &lt;em&gt;T&lt;/em&gt;  and &lt;em&gt;U&lt;/em&gt;, both argument types are the same.&lt;span style="FONT-STYLE: italic"&gt;&lt;/span&gt;&lt;/li&gt;  &lt;li&gt;  Every exception type in the throws of &lt;em&gt;T&lt;/em&gt; is a subtype of some exception type in the throws of &lt;em&gt;U&lt;/em&gt;.&lt;/li&gt; &lt;/ul&gt; &lt;p style="MARGIN-LEFT: 40px"&gt; &lt;/p&gt; &lt;p&gt;  If the closure is not passed to a parameter that was declared &lt;tt&gt;synchronized&lt;/tt&gt; then &lt;/p&gt; &lt;ul&gt;  &lt;li&gt;  it is a compile-time error if the closure being converted contains a break, continue &lt;a&gt;&lt;/a&gt;or return statement whose execution would result in a transfer of control outside the closure&lt;/li&gt;  &lt;li&gt;  it is a compile-time error if the closure being converted refers to a non-final local variable or parameter declared in an enclosing scope.&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;  The closure conversion to a non-&lt;tt&gt;synchronized&lt;/tt&gt; parameter applies only to closures that obey the same restrictions that apply to local and anonymous classes. The motivation for this is to help catch inadvertent use of non-local control flow in situations where it would be inappropriate. Examples would be when the closure is passed to another thread, or stored in a data structure to be invoked at a later time when the method invocation in which the closure originated no longer exists. &lt;/p&gt; &lt;p style="MARGIN-LEFT: 40px"&gt;  Note: The closure conversion occurs at compile-time, not at runtime. This enables javac to allocate only one object, rather than both a closure and an anonymous class instance.&lt;br/&gt; &lt;/p&gt; &lt;p style="MARGIN-LEFT: 40px"&gt; We are considering an additional qualifier on non-final local variables that allows a closure to access the variable.&lt;br/&gt; &lt;/p&gt; &lt;h3&gt; Example &lt;/h3&gt; &lt;p&gt; &lt;a&gt;&lt;/a&gt; We can use the existing &lt;code&gt;Executor&lt;/code&gt; framework to run a closure in the background: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt; void sayHello(java.util.concurrent.Executor ex) {&lt;br/&gt; ex.execute((){ System.out.println("hello"); });&lt;br/&gt; }&lt;/pre&gt; &lt;/blockquote&gt; &lt;h2&gt; 5. Exception type parameters &lt;/h2&gt; &lt;p&gt; To support exception transparency, we add a new type of generic formal type argument to receive a set of thrown types. &lt;em&gt;[This deserves a more formal treatment]&lt;/em&gt; What follows is an example of how the proposal would be used to write an exception-transparent version of a method that locks and then unlocks a &lt;tt&gt;java.util.concurrent.Lock&lt;/tt&gt;, before and after a user-provided block of code: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;interface Block&amp;lt;throws E&amp;gt; {&lt;br/&gt; void invoke() throws E;&lt;br/&gt;}&lt;br/&gt;public static &amp;lt;throws E extends Exception&amp;gt;&lt;br/&gt;void withLock(Lock lock, Block&amp;lt;E&amp;gt; block) throws E {&lt;br/&gt; try {&lt;br/&gt; lock.lock();&lt;br/&gt; block.invoke();&lt;br/&gt; } finally {&lt;br/&gt; lock.unlock();&lt;br/&gt; }&lt;br/&gt;}&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt; This can be used as follows: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;withLock(lock, (){&lt;br/&gt; System.out.println("hello");&lt;br/&gt;});&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt; &lt;a&gt;&lt;/a&gt; This uses a newly introduced form of generic type parameter. The type parameters &lt;tt&gt;E&lt;/tt&gt; are declared to be used in throws clauses. If the &lt;tt&gt;extends&lt;/tt&gt; clause is omitted, a type parameter declared with the &lt;tt&gt;throws&lt;/tt&gt; keyword is considered to extend &lt;tt&gt;Exception&lt;/tt&gt; (instead of &lt;tt&gt;Object&lt;/tt&gt;, which is the default for other type parameters). This type parameter accepts multiple exception types. For example, if you invoke it with a block that can throw &lt;tt&gt;IOException&lt;/tt&gt; or &lt;tt&gt;NumberFormatException&lt;/tt&gt; the type parameter &lt;tt&gt;E&lt;/tt&gt; would be &lt;tt&gt;IOException|NumberFormatException&lt;/tt&gt;. In those rare cases that you want to use explicit type parameters with multiple thrown types, the keyword &lt;tt&gt;throws&lt;/tt&gt; is required in the invocation, like this: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;Locks.&amp;lt;throws IOException|NumberFormatException&amp;gt;withLock(lock) {&lt;br/&gt; whatever();&lt;br/&gt;}&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt; You can think of this kind of type parameter accepting disjunction, "or" types. That is to allow it to match the exception signature of a closure that throws any number of different checked exceptions. If the block throws no exceptions, the type parameter would be the type &lt;tt&gt;null&lt;/tt&gt;. &lt;/p&gt; &lt;p&gt; Type parameters declared this way can be used only in a &lt;tt&gt;throws&lt;/tt&gt; clause or as a type argument to a generic method, interface, or class whose type argument was declared this way too. &lt;/p&gt; &lt;h2&gt; 6. Non-local control flow &lt;/h2&gt; &lt;p&gt; One purpose for closures is to allow a programmer to refactor common code into a shared utility, with the difference between the use sites being abstracted into a closure. The code to be abstracted sometimes contains a &lt;code&gt;break&lt;/code&gt;, &lt;code&gt;continue&lt;/code&gt;, or &lt;code&gt;return&lt;/code&gt; statement. This need not be an obstacle to the transformation. A &lt;code&gt;break&lt;/code&gt; or &lt;code&gt;continue&lt;/code&gt; statement appearing within a closure may transfer to any matching enclosing statement provided the target of the transfer is in the same innermost &lt;em&gt;ClassBody&lt;/em&gt;. &lt;/p&gt; &lt;p&gt; A &lt;code&gt;return&lt;/code&gt; statement always returns from the nearest enclosing method or constructor. &lt;/p&gt; &lt;p&gt; If a &lt;code&gt;break&lt;/code&gt; statement is executed that would transfer control out of a statement that is no longer executing, or is executing in another thread, the VM throws a new unchecked exception, &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt;. Similarly, an &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt; is thrown when a &lt;code&gt;continue&lt;/code&gt; statement attempts to complete a loop iteration that is not executing in the current thread. Finally, an &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt; is thrown when a return statement is executed if the method invocation to which the return statement would transfer control is not on the stack of the current thread. &lt;/p&gt; &lt;h2&gt; 7. Definite assignment &lt;/h2&gt; &lt;p&gt; The body of a closure may not assign to a final variable declared outside the closure. &lt;/p&gt; &lt;p&gt; A closure expression does not affect the DA/DU status of any variables it names.&lt;br/&gt; &lt;/p&gt; &lt;h2&gt; 8. The type &lt;code&gt;Unreachable&lt;/code&gt; &lt;/h2&gt; &lt;p&gt; We add the non-instantiable type &lt;code&gt;java.lang.Unreachable&lt;/code&gt;, corresponding to the standard type-theoretic &lt;span style="FONT-STYLE: italic"&gt;bottom&lt;/span&gt;. Values of this type appear only at points in the program that are formally unreachable. This is necessary to allow transparency for closures that do not return normally.&lt;code&gt;&lt;/code&gt; &lt;code&gt;Unreachable&lt;/code&gt; is a subtype of every type (even primitive types). No other type is a subtype of &lt;code&gt;Unreachable&lt;/code&gt;. It is a compile-time error to convert &lt;code&gt;null&lt;/code&gt; to &lt;code&gt;Unreachable&lt;/code&gt;. It is an error to cast to the type &lt;code&gt;Unreachable&lt;/code&gt;.&lt;span style="FONT-STYLE: italic"&gt;&lt;/span&gt;&lt;br/&gt; &lt;/p&gt; &lt;h3&gt; Example &lt;/h3&gt; &lt;p&gt; The following illustrates a closure being assigned to a variable of the correct type. &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;interface NullaryFunction&amp;lt;T, throws E&amp;gt; {&lt;br/&gt; T invoke() throws E;&lt;br/&gt;}&lt;br/&gt;NullaryFunction&amp;lt;Unreachable,null&amp;gt; thrower = () { throw new AssertionError(); };&lt;/pre&gt; &lt;/blockquote&gt; &lt;h2&gt;8. Unreachable statements &lt;/h2&gt;&lt;p&gt;An expression statement in which the expression is of type &lt;code&gt;Unreachable&lt;/code&gt; cannot complete normally. &lt;/p&gt;&lt;h2&gt;10. Abbreviated invocation syntax. &lt;/h2&gt; &lt;p&gt; A new invocation statement syntax is added to make closures usable for control abstraction: &lt;/p&gt; &lt;blockquote&gt; &lt;dl&gt;&lt;dt&gt;&lt;em&gt;AbbreviatedInvocationStatement&lt;/em&gt; &lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Primary&lt;/em&gt; ( &lt;em&gt;ExpressionList&lt;/em&gt; ) &lt;em&gt;Statement&lt;/em&gt; &lt;/dd&gt;&lt;dt&gt;&lt;em&gt;AbbreviatedInvocationStatement&lt;/em&gt; &lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Primary&lt;/em&gt; ( &lt;em&gt;Formals&lt;/em&gt; ) &lt;em&gt;Statement&lt;/em&gt; &lt;/dd&gt;&lt;dt&gt;&lt;em&gt;AbbreviatedInvocationStatement&lt;/em&gt; &lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Primary&lt;/em&gt; ( &lt;em&gt;Formals&lt;/em&gt; : &lt;em&gt;ExpressionList&lt;/em&gt; ) &lt;em&gt;Statement&lt;/em&gt; &lt;/dd&gt;&lt;/dl&gt; &lt;/blockquote&gt; &lt;p&gt; This syntax is a shorthand for the following statement: &lt;/p&gt; &lt;blockquote&gt; &lt;em&gt;Primary&lt;/em&gt; ( &lt;em&gt;ExpressionList&lt;/em&gt;, ( &lt;em&gt;Formals&lt;/em&gt; ) { &lt;em&gt;Statement&lt;/em&gt; } ); &lt;/blockquote&gt; &lt;p&gt;This syntax makes some kinds of closure-receiving APIs more convenient to use to compose statements. &lt;/p&gt; &lt;blockquote&gt;Note: There is some question of the correct order in the rewriting. On the one hand, the closure seems most natural in the last position when not using the abbreviated syntax. On the other hand, that doesn't work well with varargs methods. Which is best remains an open issue. &lt;/blockquote&gt; &lt;p&gt; We could use the shorthand to write our previous example this way &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;withLock(lock) {&lt;br/&gt; System.out.println("hello");&lt;br/&gt;}&lt;br/&gt;&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt; This is not an expression form for a very good reason: it looks like a statement, and we expect it to be used most commonly as a statement for the purpose of writing APIs that abstract patterns of control. If it were an expression form, an invocation like this would require a trailing semicolon after the close curly brace of a controlled block. Forgetting the semicolon would probably be a common source of error. The convenience of this abbreviated syntax is evident for both synchronous (e.g. &lt;tt&gt;withLock&lt;/tt&gt;) and asynchronous (e.g. &lt;tt&gt;Executor.execute&lt;/tt&gt;) use cases. Another example of its use would be a an API that closes a &lt;span style="FONT-FAMILY: monospace"&gt;java.io.Closeable&lt;/span&gt; after a user-supplied block of code:&lt;/p&gt;&lt;blockquote&gt;class OneArgBlock&amp;lt;T, throws E&amp;gt; {&lt;br/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; void invoke(T t) throws E;&lt;br/&gt;}&lt;br/&gt;&amp;lt;T extends java.io.Closeable, throws E&amp;gt;&lt;br/&gt;void closeAtEnd(OneArgBlock&amp;lt;? super T,E&amp;gt; block, T t) throws E {&lt;br/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; try {&lt;br/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; block.invoke();&lt;br/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } finally {&lt;br/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try { t.close(); } catch (IOException ex) {}&lt;br/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br/&gt;}&lt;br/&gt; &lt;/blockquote&gt; &lt;p&gt; We could use the shorthand with this API to close a number of streams at the end of a block of code:&lt;br/&gt; &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;closeAtEnd(FileReader in : makeReader()) closeAtEnd(FileWriter out : makeWriter()) {&lt;br/&gt; // code using in and out&lt;br/&gt;}&lt;/pre&gt; &lt;/blockquote&gt; &lt;h2&gt; Acknowledgments &lt;/h2&gt; &lt;p&gt; The authors would like to thank the following people whose discussions and insight have helped us craft, refine, and improve this proposal: &lt;/p&gt; &lt;blockquote&gt;&lt;em&gt;Lars Bak&lt;/em&gt;, &lt;em&gt;Cedric Beust&lt;/em&gt;, &lt;em&gt;Joshua Bloch&lt;/em&gt;, &lt;em&gt;Martin Buchholz&lt;/em&gt;, &lt;em&gt;Danny Coward&lt;/em&gt;, &lt;em&gt;Erik Ernst&lt;/em&gt;, &lt;em&gt;Christian Plesner Hansen, Kohsuke Kawaguchi, &lt;/em&gt;&lt;span class="q"&gt;&lt;/span&gt;&lt;em&gt;Doug Lea&lt;/em&gt;, &lt;em&gt;"crazy" Bob Lee&lt;/em&gt;, &lt;em&gt;Martin Odersky&lt;/em&gt;, &lt;em&gt;Tim Peierls&lt;/em&gt;, &lt;em&gt;John Rose&lt;/em&gt;, &lt;em&gt;Ken Russell&lt;/em&gt;, &lt;em&gt;Mads Torgersen&lt;/em&gt;, &lt;em&gt;Jan Vitek&lt;/em&gt;, and &lt;em&gt;Dave Yost&lt;/em&gt;.&lt;/blockquote&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115821034131743710?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115821034131743710' title='33 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115821034131743710'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115821034131743710'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/09/nominal-closures-for-java-version-02.html' title='Nominal Closures for Java (version 0.2)'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>33</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115768977974943416</id><published>2006-09-07T21:29:00.000-07:00</published><updated>2008-01-31T09:26:41.107-08:00</updated><title type='text'>Closures for Java (version 0.1)</title><content type='html'>&lt;span style="font-style:italic;"&gt;This post describes a draft proposal for adding support for closures to the Java programming language for the Dolphin (JDK 7) release. It was carefully designed to interoperate with the current idiom of one-method interfaces. The latest version of the proposal and a prototype can be found at &lt;a href="http://www.javac.info/"&gt;http://www.javac.info/&lt;/a&gt;.&lt;/span&gt;
&lt;p&gt;   &lt;em&gt;This revision of the proposal drops local functions and the special   nonlocal return syntax, adds support for generic type parameters that can be   used to represent thrown exceptions, and has only one form of closure literal.   It also adds an abbreviated invocation statement that supports very convenient   control abstraction. Soon I'll present a parallel proposal based on   interfaces (that is, without function types) and contrast the two proposals.&lt;/em&gt; &lt;/p&gt;&lt;p style="text-align: right;"&gt;   &lt;em&gt;Gilad &lt;a&gt;&lt;/a&gt;Bracha&lt;a&gt;&lt;/a&gt;, Neal Gafter, James Gosling, Peter von der   Ahé&lt;/em&gt; &lt;/p&gt; &lt;p&gt;   Modern programming languages provide a mixture of primitives for composing   programs. C#, Javascript, Ruby, Scala, and Smalltalk (to name just a   few) have direct language support for &lt;em&gt;function types&lt;/em&gt; and inline   function-valued expression, called &lt;em&gt;closures&lt;/em&gt;. A proposal for closures   is working its way through the C++ standards committees as well. Function   types provide a natural way to express some kinds of abstraction that are   currently quite awkward to express in Java. For programming in the small,   closures allow one to abstract an algorithm over a piece of code; that   is, they allow one to more easily extract the common parts of two   almost-identical pieces of code. For programming in the large, closures   support APIs that express an algorithm abstracted over some computational   aspect of the algorithm. We propose to add function types and closures to   Java. We anticipate that the additional expressiveness of the language will   simplify the use of existing APIs and enable new kinds of APIs that are   currently too awkward to express using the best current idiom: interfaces and   anonymous classes. &lt;/p&gt; &lt;h2&gt;1. Function Types &lt;/h2&gt; &lt;p&gt;   We introduce a new syntactic form: &lt;/p&gt; &lt;blockquote&gt; &lt;dl&gt;   &lt;dt&gt;&lt;em&gt;Type&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Type&lt;/em&gt; (   &lt;em&gt;TypeList&lt;/em&gt;&lt;sub&gt;&lt;em&gt;opt&lt;/em&gt;&lt;/sub&gt; )   &lt;em&gt;FunctionThrows&lt;sub&gt;opt&lt;/sub&gt;&lt;/em&gt;&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;FunctionThrows&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;&lt;/em&gt;&lt;code&gt;throws&lt;/code&gt;   &lt;em&gt;ThrowsTypeList&lt;/em&gt;&lt;br&gt;   &lt;/dd&gt;&lt;dt&gt;&lt;em&gt;ThrowsTypeList&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Type&lt;/em&gt;&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;ThrowsTypeList&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;ThrowsTypeList&lt;/em&gt;   VBAR &lt;em&gt;Type&lt;/em&gt;&lt;/dd&gt;&lt;dt&gt;VBAR&lt;/dt&gt;&lt;dd&gt;|&lt;/dd&gt; &lt;/dl&gt; &lt;/blockquote&gt; &lt;p&gt;   These syntactic forms designate &lt;em&gt;function types&lt;/em&gt;. A function type is a   kind of reference type. A function type consists of a return type, a list of   argument types, and a set of thrown exception types. &lt;/p&gt; &lt;p style="margin-left: 40px;"&gt;   Note: the existing syntax for the throws clause in a method declaration uses a   comma to separate elements of the &lt;em&gt;ThrowsTypeList&lt;/em&gt;. For backward   compatibility we continue to allow commas to separate these elements in   methods and constructors, but in function types we require the use of the   '&lt;code&gt;|&lt;/code&gt;' (vertical-bar) character as a separator to resolve a true ambiguity   that would arise when a function type is used in a type list. &lt;/p&gt; &lt;h2&gt;2. Namespaces and name lookup &lt;/h2&gt; &lt;p&gt;   The Java programming language currently maintains a strict separation between   &lt;em&gt;expression names&lt;/em&gt; and &lt;em&gt;method names&lt;/em&gt;. These two separate   namespaces allow a programmer to use the same name for a variable and for   methods. Variables of closure type necessarily blur the distinction between   these two namespaces, because they can be used in an expression and they can   be invoked. &lt;/p&gt; &lt;p&gt;   When searching a scope for a method name, if no methods exist with the given   name then variables of the given name that are of function type are considered   candidates. If more than one exists (for example, function-typed variable   declarations are inherited from separate supertypes), the reference is   considered ambiguous. &lt;/p&gt; &lt;p&gt;   We allow a function to be invoked from an arbitrary (for example,   parenthesized) expression: &lt;/p&gt; &lt;blockquote&gt; &lt;dl&gt;   &lt;dt&gt;&lt;em&gt;Primary&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Primary&lt;/em&gt; &lt;em&gt;Arguments&lt;/em&gt;&lt;/dd&gt; &lt;/dl&gt; &lt;/blockquote&gt; &lt;h2&gt;3. Closure Literals &lt;/h2&gt; &lt;p&gt;   We also introduce a syntactic form for constructing a value of function type: &lt;/p&gt; &lt;blockquote&gt; &lt;dl&gt;   &lt;dt&gt;&lt;em&gt;Expression3&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Closure&lt;/em&gt;&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;Closure&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;FormalParameters&lt;/em&gt;   { &lt;em&gt;BlockStatements&lt;sub&gt;opt&lt;/sub&gt;&lt;/em&gt; &lt;em&gt;Expression&lt;sub&gt;opt&lt;/sub&gt;&lt;/em&gt;   }&lt;/dd&gt; &lt;/dl&gt; &lt;/blockquote&gt; &lt;h3&gt;   Example &lt;/h3&gt; &lt;p&gt;   We can write a function that adds two to its argument like this: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;    int(int) plus2 = (int x){ x+2 };&lt;/pre&gt; &lt;/blockquote&gt; &lt;h2&gt;4. The type of a closure &lt;/h2&gt; &lt;p&gt;   The type of a closure is inferred from its form as follows: &lt;/p&gt; &lt;p&gt;   The argument types of a closure are the types of the declared arguments. &lt;/p&gt; &lt;p&gt;   If the body of the closure ends with an expression, the return type of the   closure is the type of that expression; otherwise if the closure can complete   normally, the return type is &lt;code&gt;void&lt;/code&gt;; otherwise the return type is &lt;code&gt;null&lt;/code&gt;. &lt;/p&gt; &lt;p&gt;   The set of thrown types of a closure are those checked exception types thrown   by the body. &lt;/p&gt; &lt;h3&gt;   Example &lt;/h3&gt; &lt;p&gt;   The following illustrates a closure being assigned to a variable with   precisely the type of the closure. &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;void(int) throws InterruptedException sleeper = (int t) { Thread.sleep(t); };&lt;/pre&gt; &lt;/blockquote&gt; &lt;h2&gt;5. Subtyping &lt;/h2&gt; &lt;p&gt;   A function type &lt;em&gt;T&lt;/em&gt; is a subtype of function type &lt;em&gt;U&lt;/em&gt; iff all of   the following hold: &lt;/p&gt; &lt;ul&gt;   &lt;li&gt;     Either     &lt;ul&gt;       &lt;li&gt;         The return type of &lt;em&gt;T&lt;/em&gt; is either the same as the return type of         &lt;em&gt;U&lt;/em&gt; or&lt;/li&gt;       &lt;li&gt;         Both return types are reference types and the return type of &lt;em&gt;T&lt;/em&gt;         is a subtype of the return type of &lt;em&gt;U&lt;/em&gt;, or&lt;/li&gt;       &lt;li&gt;         the return type of &lt;em&gt;U&lt;/em&gt; is &lt;code&gt;void&lt;/code&gt;.&lt;/li&gt;     &lt;/ul&gt;&lt;/li&gt;   &lt;li&gt;     &lt;em&gt;T&lt;/em&gt; and &lt;em&gt;U&lt;/em&gt; have the same number of declared arguments.&lt;/li&gt;   &lt;li&gt;     For each corresponding argument position in the argument list of &lt;em&gt;T&lt;/em&gt;     and &lt;em&gt;U&lt;/em&gt;, either both argument types are the same or both are     reference types and the type of the argument to &lt;em&gt;U&lt;/em&gt; is a subtype of     the corresponding argument to &lt;em&gt;T&lt;/em&gt;.&lt;/li&gt;   &lt;li&gt;     Every exception type in the throws of &lt;em&gt;T&lt;/em&gt; is a subtype of some     exception type in the throws of &lt;em&gt;U&lt;/em&gt;.&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;6. Exception checking &lt;/h2&gt; &lt;p&gt;   The invocation of a function throws every checked exception type in the   function's type. &lt;/p&gt; &lt;h2&gt;7. Reflection &lt;/h2&gt; &lt;p&gt;   A function type inherits all the non-private methods from &lt;code&gt;Object&lt;/code&gt;. The following   methods are added to &lt;code&gt;java.lang.Class&lt;/code&gt; to support function types: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;  public final class java.lang.Class ... {&lt;br&gt;      public boolean isFunction();&lt;br&gt;      public java.lang.reflect.FunctionType functionType();&lt;br&gt;      public Object invokeFunction(Object function, Object ... args)&lt;br&gt;         throws IllegalArgumentException | InvocationTargetException;&lt;br&gt;  }&lt;br&gt;  public interface java.lang.reflect.FunctionType {&lt;br&gt;      public Type returnType();&lt;br&gt;      public Type[] argumentTypes();&lt;br&gt;      public Type[] throwsTypes();&lt;br&gt;  }&lt;/pre&gt; &lt;/blockquote&gt; &lt;p style="margin-left: 40px;"&gt;   Note: unlike &lt;code&gt;java.lang.reflect.Method.invoke&lt;/code&gt;, &lt;code&gt;Class.invokeFunction&lt;/code&gt; cannot throw &lt;code&gt;IllegalAccessException&lt;/code&gt;, because there is no access   control to enforce; the function value designates a closure, which does not   have access modifiers. Access to function values is controlled at compile-time   by their &lt;em&gt;scope,&lt;/em&gt; and at runtime by controlling the function value. &lt;/p&gt; &lt;h2&gt;8. The type of &lt;code&gt;null&lt;/code&gt; &lt;/h2&gt; &lt;p&gt;   We add support for &lt;code&gt;null&lt;/code&gt; and the type of &lt;code&gt;null&lt;/code&gt; in function types. We introduce   a meaning for the keyword &lt;code&gt;null&lt;/code&gt; as a type name; it designates the type of the   expression &lt;code&gt;null&lt;/code&gt;. A class literal for the type of &lt;code&gt;null&lt;/code&gt; is &lt;code&gt;null.class&lt;/code&gt;. These are   necessary to allow reflection, type inference, and closure literals to work   for functions that do not return normally. We also add the non-instantiable   class &lt;code&gt;java.lang.Null&lt;/code&gt; as a placeholder, and its static member field &lt;code&gt;TYPE&lt;/code&gt; as a synonym   for &lt;code&gt;null.class&lt;/code&gt;. &lt;/p&gt; &lt;h2&gt;9. Referencing names from the enclosing scope &lt;/h2&gt; &lt;p&gt;   Names that are in scope where a closure is defined may be   referenced within the closure. We do not propose a rule that requires   referenced variables be final, as is currently required for anonymous class   instances. &lt;/p&gt; &lt;blockquote&gt; Note: a local variable that is referenced within a closure is in scope in the body of the closure. Consequently the lifetime of objects referenced by such variables may extend beyond the time that the block containing the local declaration completes. &lt;/blockquote&gt; &lt;h2&gt;10. Non-local control flow &lt;/h2&gt; One purpose for closures is to allow a programmer to refactor common code into a shared utility, with the difference between the use sites being abstracted into a closure. The code to be abstracted sometimes contains a &lt;code&gt;break&lt;/code&gt;, &lt;code&gt;continue&lt;/code&gt;, or &lt;code&gt;return&lt;/code&gt; statement. This need not be an obstacle to the transformation. A &lt;code&gt;break&lt;/code&gt; or &lt;code&gt;continue&lt;/code&gt; statement appearing within a closure may transfer to any matching enclosing statement provided the target of the transfer is in the same innermost &lt;em&gt;ClassBody&lt;/em&gt;. &lt;p&gt;   A &lt;code&gt;return&lt;/code&gt; statement always returns from the nearest enclosing method or   constructor. &lt;/p&gt; &lt;p&gt;   If a &lt;code&gt;break&lt;/code&gt; statement is executed that would transfer control out of a   statement that is no longer executing, or is executing in another thread, the   VM throws a new unchecked exception, &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt;. (I suspect we can come up with a   better name). Similarly, an &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt; is thrown when a &lt;code&gt;continue&lt;/code&gt; statement attempts to   complete a loop iteration that is not executing in the current thread.   Finally, an &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt; is thrown when a &lt;em&gt;NamedReturnStatement&lt;/em&gt; attempts to   return from a function or method invocation that is not pending in the current   thread. Likewise, an &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt; is thrown when a return statement is executed if   the method invocation to which the return statement would transfer control is   not on the stack of the current thread. &lt;/p&gt; &lt;h2&gt;11. Closure conversion &lt;/h2&gt; &lt;p&gt;   We propose the following closure conversion, to be applied only in those   contexts where boxing currently occurs: &lt;/p&gt; &lt;p style="margin-left: 40px;"&gt;   There is a &lt;em&gt;closure conversion&lt;/em&gt; from every closure of type T to every   interface type that has a single method with signature U such that T is a   subtype of the function type corresponding to U. &lt;/p&gt; &lt;p style="margin-left: 40px;"&gt;   It is a compile-time error if the closure being converted contains a break,   continue or return statement whose execution could result in a transfer of   control outside the closure. It is a compile-time error if the closure being   converted refers to a non-final local variable or parameter declared in an   enclosing scope. &lt;/p&gt; &lt;p&gt;   We will want to generalize this rule slightly to allow the conversion when   boxing or unboxing of the return type is required, e.g. to allow assigning a   closure that returns &lt;code&gt;int&lt;/code&gt; to an interface whose method returns &lt;code&gt;Integer&lt;/code&gt; or vice   versa. &lt;/p&gt; &lt;p style="margin-left: 40px;"&gt;   Note: the closure conversion is applied only to closures (i.e. function   literals), not to arbitrary expressions of function type. This enables javac   to allocate only one object, rather than both a closure and an anonymous class   instance. The conversion avoids hidden overhead at runtime. As a practical   matter, javac will automatically generate code equivalent to our original   client, creating an anonymous class instance in which the body of the lone   method corresponds to the body of the closure. &lt;/p&gt; &lt;p&gt;   Closure conversion applies only to closures that obey the same restrictions   that apply to local and anonymous classes. The motivation for this is to help   catch inadvertent use of non-local control flow in situations where it would   be inappropriate. Examples would be when the closure is passed to another   thread, or stored in a data structure to be invoked at a later time when the   method invocation in which the closure originated no longer exists. &lt;/p&gt; &lt;h3&gt;   Examples &lt;/h3&gt; &lt;p&gt;   We can use the existing &lt;code&gt;Executor&lt;/code&gt; framework to run a closure in the background: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;  void sayHello(java.util.concurrent.Executor ex) {&lt;br&gt;      ex.execute((){ System.out.println("hello"); });&lt;br&gt;  }&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt;Here is a definition of an API that locks and then unlocks a &lt;tt&gt;java.util.concurrent.Lock&lt;/tt&gt;, before and after a user-provided block of code:&lt;/p&gt; &lt;blockquote&gt;&lt;pre&gt;public static &amp;lt;E extends Exception&amp;gt;&lt;br&gt;void withLock(Lock lock, void() throws E block) throws E {&lt;br&gt;    try {&lt;br&gt;        lock.lock();&lt;br&gt;        block();&lt;br&gt;    } finally {&lt;br&gt;        lock.unlock();&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt;This can be used as follows: &lt;/p&gt;&lt;blockquote&gt; &lt;pre&gt;withLock(lock, (){&lt;br&gt;    System.out.println("hello");&lt;br&gt;});&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt;You might find this syntax a bit tedious. Not to worry - see below. &lt;/p&gt;&lt;h2&gt;12. Abbreviated invocation syntax. &lt;/h2&gt; &lt;p&gt;A new invocation statement syntax is added to make closures usable for control abstraction: &lt;/p&gt;&lt;blockquote&gt; &lt;dl&gt;   &lt;dt&gt;&lt;em&gt;AbbreviatedInvocationStatement&lt;/em&gt; &lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Primary&lt;/em&gt; (   &lt;em&gt;ExpressionList&lt;/em&gt; ) &lt;em&gt;Block&lt;/em&gt;   &lt;/dd&gt;&lt;dt&gt;&lt;em&gt;AbbreviatedInvocationStatement&lt;/em&gt; &lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Primary&lt;/em&gt; (   &lt;em&gt;Formals&lt;/em&gt; ) &lt;em&gt;Block&lt;/em&gt;   &lt;/dd&gt;&lt;dt&gt;&lt;em&gt;AbbreviatedInvocationStatement&lt;/em&gt; &lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Primary&lt;/em&gt; (   &lt;em&gt;Formals&lt;/em&gt; : &lt;em&gt;ExpressionList&lt;/em&gt; ) &lt;em&gt;Block&lt;/em&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;/blockquote&gt; &lt;p&gt;   This syntax is a shorthand for the following statement: &lt;/p&gt; &lt;blockquote&gt; &lt;em&gt;Primary&lt;/em&gt; ( &lt;em&gt;ExpressionList&lt;/em&gt;, ( &lt;em&gt;Formals&lt;/em&gt; ) &lt;em&gt;Block&lt;/em&gt; ); &lt;/blockquote&gt; &lt;p&gt;   Note that this syntax is only a convenience to make some kinds of   closure-receiving APIs more convenient to use to compose statements. &lt;/p&gt; &lt;p&gt;   We could use the shorthand to write our previous example this way &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;withLock(lock) {&lt;br&gt;    System.out.println("hello");&lt;br&gt;}&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt;   This is not an expression form for a very good reason: it looks like a   statement, and we expect it to be used most commonly as a statement for the   purpose of writing APIs that abstract patterns of control. If it were an   expression form, an invocation like this would require a trailing semicolon   after the close curly brace. Forgetting the semicolon would probably be a   common source of error. The convenience of this abbreviated syntax is evident   for both synchronous (e.g. &lt;tt&gt;withLock&lt;/tt&gt;) and asynchronous (e.g. &lt;tt&gt;Executor.execute&lt;/tt&gt;) use cases. &lt;/p&gt; &lt;h2&gt;13. Definite assignment &lt;/h2&gt; &lt;p&gt;The body of a closure may not assign to a final variable declared outside the closure. &lt;/p&gt;&lt;p&gt;A closure expression does not affect the DA/DU status of any variables it names.&lt;br&gt; &lt;/p&gt;&lt;h2&gt;14. Exception type parameters &lt;/h2&gt; &lt;p&gt;   To support exception transparency, we add a new type of generic formal type   argument to receive a set of thrown types. &lt;em&gt;[This deserves a more formal   treatment]&lt;/em&gt; What follows is an example of how the proposal would be used   to write an exception-transparent version of the withLock() example we've been   using. The syntax is quite tentative at this point (ideas are welcome). &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;public static &amp;lt;throws E extends Exception&amp;gt;&lt;br&gt;void withLock(Lock lock, void() throws E block) throws E {&lt;br&gt;    try {&lt;br&gt;        lock.lock();&lt;br&gt;        block();&lt;br&gt;    } finally {&lt;br&gt;        lock.unlock();&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt;   This method uses a newly introduced form of generic type parameter. The type   parameter &lt;tt&gt;E&lt;/tt&gt; is declared to be used in throws clauses. If the &lt;tt&gt;extends&lt;/tt&gt; clause is   omitted, a type parameter declared with the &lt;tt&gt;throws&lt;/tt&gt; keyword is considered to   extend &lt;tt&gt;Exception&lt;/tt&gt; (instead of &lt;tt&gt;Object&lt;/tt&gt;, which is the default for other type parameters).   This type parameter accepts multiple exception types. For example, if you   invoke it with a block that can throw &lt;tt&gt;IOException&lt;/tt&gt; or &lt;tt&gt;NumberFormatException&lt;/tt&gt; the type parameter &lt;tt&gt;E&lt;/tt&gt; would   be &lt;tt&gt;IOException|NumberFormatException&lt;/tt&gt;. In those rare cases that you want to use explicit type parameters, the   keyword &lt;tt&gt;throws&lt;/tt&gt; is required in the invocation, like this: &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;Locks.&amp;lt;throws IOException|NumberFormatException&amp;gt;withLock(lock) {&lt;br&gt;    whatever();&lt;br&gt;}&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt;   You   can think of this kind of type parameter accepting disjunction, "or" types.   That is to allow it to match the exception signature of a closure that throws   any number of different checked exceptions. If the block throws no exceptions,   the type parameter would be the type &lt;tt&gt;null&lt;/tt&gt;. &lt;/p&gt; &lt;p&gt;   Type parameters declared this way   can be used only in a &lt;tt&gt;throws&lt;/tt&gt; clause or as a type argument to a generic method,   interface, or class whose type argument was declared this way too. &lt;/p&gt; &lt;h2&gt;15. Implementing a Function Type &lt;/h2&gt; &lt;p&gt;   A programmer may write a class that implements a function type. The   implementation is written as a public method with the keyword &lt;tt&gt;do&lt;/tt&gt; in place of   the method's identifier. For example &lt;/p&gt; &lt;blockquote&gt; &lt;pre&gt;class MyBlock implements void() {&lt;br&gt;    public void do() {&lt;br&gt;        // implementation of the function&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;/pre&gt; &lt;/blockquote&gt; &lt;p&gt;   In this way programmers can, for example, create implementations of function   types that are serializable. &lt;/p&gt; &lt;h2&gt;   Acknowledgments &lt;/h2&gt; &lt;p&gt;   The authors would like to thank the following people whose discussions and   insight have helped us craft, refine, and improve this proposal: &lt;/p&gt; &lt;blockquote&gt;&lt;em&gt;Lars Bak&lt;/em&gt;, &lt;em&gt;Cedric Beust&lt;/em&gt;, &lt;em&gt;Joshua Bloch&lt;/em&gt;, &lt;em&gt;Martin Buchholz&lt;/em&gt;, &lt;em&gt;Danny Coward&lt;/em&gt;, &lt;em&gt;Erik Ernst&lt;/em&gt;, &lt;em&gt;Christian Plesner Hansen&lt;/em&gt;, &lt;em&gt;Doug Lea&lt;/em&gt;, &lt;em&gt;"crazy" Bob Lee&lt;/em&gt;, &lt;em&gt;Martin Odersky&lt;/em&gt;, &lt;em&gt;Tim Peierls&lt;/em&gt;, &lt;em&gt;John Rose&lt;/em&gt;, &lt;em&gt;Ken Russell&lt;/em&gt;, &lt;em&gt;Mads Torgersen&lt;/em&gt;, &lt;em&gt;Jan Vitek&lt;/em&gt;, and &lt;em&gt;Dave Yost&lt;/em&gt;.&lt;/blockquote&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115768977974943416?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115768977974943416' title='12 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115768977974943416'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115768977974943416'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/09/closures-for-java-version-01.html' title='Closures for Java (version 0.1)'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>12</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115760164031466812</id><published>2006-09-06T21:00:00.000-07:00</published><updated>2007-08-13T08:28:50.027-07:00</updated><title type='text'>The Debate over Closures for Java</title><content type='html'>&lt;p&gt;     We've been continuing work on the closures proposal. I'd like to give you     some feedback on what I think about the debate. Tomorrow I'll post an     updated proposal, and the next day I'll outline an alternative version of     the proposal that avoids function types and contrast it with the current     draft; some people think that might be a better approach, though we have     some doubts that I'll explain.   &lt;/p&gt;   &lt;p&gt;     Our publication of the draft closures proposal resulted in a great deal of     debate and excitement. Even if we end up doing nothing, I think that is very     healthy. These kind of things rarely get debated in such public forums.     We've been listening to the debate as it rages (on scores of blogs and     message boards, and the occasional email), and we're trying to adjust our     thinking accordingly. My next post will be an updated version of the     proposal, and the following will be an extended discussion of one     alternative direction we're considering that addresses some concerns.   &lt;/p&gt;   &lt;p&gt;     There are a few different kinds of feedback we've received, both positive     and negative. To those whose feedback has been mostly positive: you've been     no help whatsoever. Just kidding. Seriously, thanks for the support. We     don't think things are perfect yet, and maybe they will never even be good     enough to put anything like closures in the Java programming language. We     need to figure out what, if anything, to change to make it better, so your     criticism is welcome. If you can quantify precisely how much more fun Java     will be to program in, that would help too.   &lt;/p&gt;   &lt;p&gt;     To those with mainly negative or mixed feedback, I'd like to try to classify     some of the most common concerns and give general, blanket responses. Please     don't take these to mean we're dismissing your concerns. On the contrary, we     expect the proposal to evolve, and your concerns are a primary source of     information on how the proposal needs to evolve. This classification doesn't     cover all the constructive criticism we've received or all the issues we     know we need to address, and there is a great deal of overlap between these     topics.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;Closures don't buy you anything beyond what you can accomplish with inner     classes.&lt;/b&gt; That just isn't true. See     &lt;a href="http://gafter.blogspot.com/2006/08/use-cases-for-closures.html"&gt;my     previous blog post about use cases&lt;/a&gt;. Interfaces and inner classes solve     the asynchronous use cases just fine, mostly, but they don't touch the     synchronous use cases. I don't mean to imply that they can't be extended to     cover both sets of use cases, but inner classes in their current form don't     do it.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;The addition of &lt;em&gt;function types&lt;/em&gt; to the language is too much of a     price to pay for closures.&lt;/b&gt; We have a few reactions to this. First,     you're likely to be surprised how much you actually get with closures, and     how little it actually costs you in complexity. While it might be possible     to get closures without function types - see the alternative proposal for     one stab at that approach - what you lose doing things that way is not     trivial.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;The structural typing of function types doesn't feel right in Java, which     normally does its typing via programmer-defined named types.&lt;/b&gt; Actually,     function types dovetail nicely with interfaces due to the closure     conversion. The structural typing you get with closures is much like you     would get using generic interfaces and using wildcards heavily in your code,     except much simpler.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;The proposal introduces a second way to do things that folks already do     with interfaces.&lt;/b&gt; The concern here is that the language should provide     strong guidance on how to do any particular kind of thing, and Java has     already chosen to pass snippets of code around as objects that implement     interfaces, typically via anonymous classes. Moreover, some existing APIs     might look silly doing things the "wrong" way once a new way is introduced.     I don't think this concern holds water because virtually all of the existing     APIs in the JDK that I'm aware of are best written using interfaces rather     than function types. I've heard the debate regarding the JDK notification     APIs (for example, in swing) and what to do about them. I think they should     be left alone.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;Ordinary Java programmers won't be able to understand this stuff.&lt;/b&gt;     Many folks who say this don't make it clear which parts of the proposal they     find most troubling, or perhaps they don't see the proposal as decomposable     into troubling and acceptable parts. The &lt;em&gt;Closures for Java&lt;/em&gt; draft     specification was written to be more like a specification than a tutorial.     It is not a suitable thing to read to learn the language construct, any more     than reading the &lt;em&gt;Java Language Specification&lt;/em&gt; is a suitable way to learn object-oriented programming. Rather you would learn the feature     by examples of gradually increasing complexity. I haven't provided that, and     I apologize. I've tried to remedy that in my later blog posts but I'm afraid     I'm not very good at that kind of writing.   &lt;/p&gt;   &lt;p&gt;     If you believe that closures are inherently a difficult concept for     programmers to understand, or some kind of language "trickery", I suspect     you probably haven't done much coding in a language that supports them (see Steve Yegge's     blog post     &lt;a href="http://www.cabochon.com/%7Estevey/blog-rants/language-trickery-ejb.html"&gt;&lt;em&gt;     Language Trickery and EJB&lt;/em&gt;&lt;/a&gt;, and Curtis Poe's article     &lt;a href="http://www.oreillynet.com/onlamp/blog/2006/05/sapirwhorf_is_not_a_klingon.html"&gt;     &lt;em&gt;Sapir-Whorf is not a Klingon&lt;/em&gt;&lt;/a&gt;). In     practice they are pretty straightforward and obvious. Things are complex with anonymous     inner classes, and any tutorial would need to explain them as well. I will     present an alternative spec in a few days that does away with function types     entirely, syntax and all; with that change the spec may seem simpler than     the previous one, but I believe as a practical matter it will be harder to     use. Also gone are local functions from our proposal entirely. Those who     identified function types as the main problem might be satisfied with the     version of the proposal lacking function types. But if you have a hard time     understanding anonymous inner classes, closures won't make things any easier     as we can't remove anything from the language. There also needs to be a     prototype implementation that people can actually use to get a feel for what     closures can do. I eagerly await an open-source &lt;tt&gt;javac&lt;/tt&gt; on which we can     prototype this.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;How much more expressive does the language become given the complexity of     the additions?&lt;/b&gt; The gist of this concern is that adding closures seems to     increase the complexity of the language substantially. Is the additional     expressiveness worth the additional complexity? The best result would that     we end up with an expressive &lt;em&gt;but simple&lt;/em&gt; programming langauge. The     question is: how much more expressive can you get with minimal changes to     the language? We believe that closures adds significantly to the     expressiveness of Java in an area that the language is severly lacking. The     asynchronous use cases are handled just fine today, but the synchronous use     cases like control abstraction and some kinds of functional programming     idioms are very difficult.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;Are you just doing this to compete with C#/Ruby/Javascript or add the     latest experimental/research language feature?&lt;/b&gt; Closures have been an     idea simmering in the background since the earliest days of Java, and it is     the subject of repeated RFEs. Closures predate Java by many years. Closures     were in Simula (the original object-oriented language), Lisp, and Smalltalk.     They really do make some things easy that are difficult or impossible to     express without them. Anonymous inner classes were a half-measure that made     some use cases easier, but left some use cases unaddressed. Competition from     other languages has shaped the political landscape and the programmer     mindset to make closures more acceptable than they were before, so the time     is ripe to propose them.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;Values of function type can't be made serializable.&lt;/b&gt; Agreed, a problem     in the previous spec. We intend that you should be allowed to "implement"     function types so that you can make them serializable.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;I can't stand the syntax.&lt;/b&gt; We've heard this before about things that     people ended up loving once they started using them. We're open to     alternatives. The alternative of just using anonymous class instance     creation expressions doesn't work. Closures are not just shorthand for     making an anonymous class, because names appearing inside the closure are     resolved in the context of the enclosing scope instead of in the context of     the anonymous class being created. Perhaps there is a better way of writing     a function type. Perhaps we can improve the syntax for writing a closure -     but it does require its own distinct syntax in order to get the expressive     power. Your suggestions and ideas are welcome.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;The synchronous and asynchronous use cases are so different that they     deserve completely different syntax.&lt;/b&gt; I'm not sure about this argument. First, in the proposal the two kinds of APIs do use completely different syntaxes: one uses function types and the other uses interfaces. A     closure means precisely the same thing (if it is allowed) whether used in     one kind of API or the other. Any difference in meaning is because of what     the API elects to do with the closure (for example, invoke it or not invoke     it). Therefore, to understand a use of a closure, you need to consult the     documentation or specification of the method it is passed to. In this     respect a closure is no different than a value of any other type. I suspect     I don't fully understand this concern, and we'll keep listening.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;Closures will be implemented using the JVM &lt;tt&gt;invokedynamic&lt;/tt&gt; bytecode; won't that hurt     performance?&lt;/b&gt; The short answer is: no, not necessarily, and there are     alternative implementation strategies that use existing instructions.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;Compatibility with the existing language demands an inelegant/kludgy     design for closures.&lt;/b&gt; Frankly, I don't believe it. I believe that the     Java language in JDK7 can have closures AND seem to have been designed with     them from the beginning, with virtually all existing APIs using the most     appropriate idiom. Some minor syntactic challenges remain: closures would     probably better be written with a new keyword (lambda? fun?), but can't due     to backward compatibility; a related issue is the difficulty of using "," or     "|" in the syntax for disjunction types for type parameters representing     thrown exception types. I believe we are likely to converge on a syntax that     feels quite natural once people start trying to use it.   &lt;/p&gt;   &lt;p&gt;     A related argument compares the Java programming language to a delicious     Oreo® Cookie: &lt;b&gt;you can add syntactic sugar to its outside and still have a     nice Oreo cookie, but if you disturb its delicious design center it just     won't be the same anymore.&lt;/b&gt; Implicit in this argument is a warning (or     veiled threat) that hordes of Java programmers will abandon the platform if     anything so horrible is done to the language. I think this line of reasoning     is overly melodramatic. In fact, I believe the addition of closures will     attract a number of programmers who have previously had no choice but to     seek alternative languages due to limitations of Java.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;Closures are too powerful; programmers should not have the freedom to     effectively define their own control constructs, because they will write     programs that are too hard to understand.&lt;/b&gt; Instead, the argument goes, we     should add new statements to the language for each of the important use     cases we know about and leave it at that. The gist of this concern is that     while the Java programming language today lends itself to easily understood     programs, the addition of closures will result in a language in which     readers of programs have no firm ground to stand on, and will not be able to     tell what a program means. I've only heard this concern raised by a small     number of people and our response (thanks to James Gosling) is: &lt;em&gt;by the     same logic we shouldn't allow programmers to write their own methods     either&lt;/em&gt;. If you're reading a program with invocations of unfamiliar     methods, you may have to consult the documentation of those methods to     understand what the code does; if the code is well-written the name of the     method will give you a good hint. This is true whether or not the method     receives a closure as an argument. Related to this argument is the concern     that the addition of closures will make it possible to write programs that     are really hard to understand, but in reality poor programs can be written     in any language. This line of reasoning is made by those who consider     themselves advocates of the B&amp;D (Bondage and Discipline) school of     language design, but I would characterize it as the S&amp;M (Sadism and     Masochism) school. The subtext is that we should not trust ordinary     programmers with anything so expressive as closures.   &lt;/p&gt;   &lt;p&gt;     &lt;b&gt;Closures should work with classes that have a single abstract method,     like &lt;tt&gt;java.util.TimerTask&lt;/tt&gt;, in addition to single-method interfaces.&lt;/b&gt; OK, sure, that sounds     like a good idea.   &lt;/p&gt;   &lt;p&gt;     There have also been proponents of various other languages like Smalltalk,     Ruby, and Javascript noting with smug amusement that the Java folks (or some     of them, anyway) finally "get" closures. To them I say "Pfffft!"   &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115760164031466812?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115760164031466812' title='15 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115760164031466812'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115760164031466812'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/09/debate-over-closures-for-java.html' title='The Debate over Closures for Java'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>15</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115752598843176617</id><published>2006-09-05T23:58:00.000-07:00</published><updated>2006-10-13T10:42:10.987-07:00</updated><title type='text'>Control abstraction</title><content type='html'>&lt;p&gt;All of the examples of synchronous use cases for closures that 
  I've shown so far fall into the general category of &lt;em&gt;control 
  abstraction&lt;/em&gt;.  The idea is that you have a common pattern 
  appearing in your code, and you want to abstract the common parts 
  while allowing the caller to provide the parts that differ. You can 
  think of these use cases as satisfying a desire to extend the set of 
  statements available in the language.  Java is already pretty good 
  at data abstraction, but not so good for control abstraction. 
 
  &lt;p&gt;Thanks to &lt;a 
  href="http://jroller.com/page/javay?entry=a_simple_demo_of_proposed"&gt;a 
  blogger whom I can't identify&lt;/a&gt;, I have another simple use case 
  for closures of the synchronous variety (still control abstraction, though).
  I would love to be able to use 
  this in the implementation of my project, &lt;a 
  href="http://www.google.com/calendar"&gt;Google Calendar&lt;/a&gt; to 
  simplify the code in hundreds of places. 
 
  &lt;p&gt;Many places throughout our code we have this pattern appearing: 
 
  &lt;blockquote&gt;&lt;pre&gt; 
void someOperation() throws SomeException { 
    long t0 = System.nanoTime(); 
    boolean success = false; 
    try { 
        someOperationInternal(); // may fail, throwing SomeException 
        success = true; 
    } finally { 
        long elapsed = System.nanoTime() - t0; 
        logElapsedTime("someOperation", success, elapsed); 
    } 
}&lt;/pre&gt;&lt;/blockquote&gt; 
 
  &lt;p&gt;The presence of this code helps us with realtime (i.e. elapsed 
  time) performance measurement, but it clutters up our code and tends 
  to obscure the logic of the application.  We would prefer to write a 
  &lt;tt&gt;timeOperation&lt;/tt&gt; method once, thereby enabling us to write the 
  above code as follows: 
 
  &lt;blockquote&gt;&lt;pre&gt; 
void someOperation() throws SomeException { 
    timeOperation("someOperation", (){ 
        someOperationInternal(); // may fail, throwing SomeException 
    }); 
}&lt;/pre&gt;&lt;/blockquote&gt; 
 
  &lt;p&gt;Or, better yet, (presuming the language supports the abbreviated 
  invocation syntax that I'll describe in a future post) 


  &lt;blockquote&gt;&lt;pre&gt; 
void someOperation() throws SomeException { 
    timeOperation("someOperation") { 
        someOperationInternal(); // may fail, throwing SomeException 
    } 
}&lt;/pre&gt;&lt;/blockquote&gt; 
 
  &lt;p&gt;The &lt;tt&gt;timeOperation&lt;/tt&gt; method can be written (once) as follows: 
 
  &lt;blockquote&gt;&lt;pre&gt; 
&amp;lt;E extends Exception&amp;gt; 
void timeOperation(String operationName, void() throws E block) throws E { 
    long t0 = System.nanoTime(); 
    boolean success = false; 
    try { 
        block(); 
        success = true; 
    } finally { 
        long elapsed = System.nanoTime() - t0; 
        logElapsedTime(operationName, success, elapsed); 
    } 
}&lt;/pre&gt;&lt;/blockquote&gt; 
 
  &lt;p&gt;This is the best way I've seen to remove this kind of redundant 
  code that is currently repeated hundreds of times throughout our 
  application.  This example should help illustrate why &lt;em&gt;closures 
  will help make code much easier to read.&lt;/em&gt; Certainly timing 
  support could instead be done with an additional extension to the 
  Java language: a new statement for timing blocks of code.  Do you 
  also add a new statement for closing your streams at the end of a 
  block, and one for locking and unlocking your 
  &lt;tt&gt;java.util.concurrent&lt;/tt&gt; locks around a block of code?  Once 
  you start down that path, where does it all end?  We'd prefer to 
  give ordinary programmers the ability to write these kinds of 
  methods (and perhaps place some of them into the JDK) rather than 
  adding a series of language extensions to address particular use 
  cases. 
 
  &lt;p&gt;Besides control abstraction, there are also important synchronous 
  use cases for closures inspired by functional programming idioms 
  with a very different feel, and I'll blog about that separately.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115752598843176617?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115752598843176617' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115752598843176617'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115752598843176617'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/09/control-abstraction.html' title='Control abstraction'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115653428620891109</id><published>2006-08-25T12:20:00.000-07:00</published><updated>2006-10-13T10:42:10.913-07:00</updated><title type='text'>Use cases for closures</title><content type='html'>&lt;p&gt;Some people have been reacting to this proposal as if it
    represents Sun's plans for the future of the language.  At this
    stage it is just some ideas being drawn up to address a number of
    requirements in a clean and uniform framework.  Other people are
    working on alternative proposals, and I expect you'll see those
    soon.  It is too early to place bets on what, if anything, Sun
    will do in this space for JDK7.

    &lt;p&gt;With the insights described in my last blog entry, we no longer
    need two separate syntactic forms for closures.  We also don't
    need the "labelled" nonlocal return statement.  We're updating the
    draft spec with this and other changes, making it more precise,
    and adding a bit of rationale.  I hope to augment the brief
    rationale that will appear in the draft with further explanation
    here.

    &lt;h2&gt;Closures, Inner Classes, and Concurrency&lt;/h2&gt;

    &lt;p&gt;Our "solution" to concurrency issues in the original version of
    the proposal was quite unsatisfying. Part of the problem was that
    we could see no way to satisfy the requirements of that community
    while preserving some of the most useful features of closures and
    without violating the language design principles.  Since then,
    we've been reexamining the issue, and I think we've found a very
    tidy solution.

    &lt;h2&gt;Asynchronous use cases&lt;/h2&gt;

    &lt;p&gt;To understand the solution, it is useful to characterize the
    use cases for closures into two very distinct categories.  The
    first category, which I'll call &lt;em&gt;asynchronous&lt;/em&gt;, are those
    in which the user-privided code is not called immediately by the
    API, but rather is saved to be executed from another thread or at
    a later time.  This includes asynchronous notification frameworks,
    the concurrency framework's executors, and timer tasks.  Generally
    speaking these fall into a pattern in which the caller of the API
    controls &lt;em&gt;what&lt;/em&gt; will be done, but the API controls
    &lt;em&gt;when&lt;/em&gt; it will be done.  These kinds of Java APIs are
    widespread in practice, and are often expressed using
    single-method interfaces or abstract classes.  Because the code
    passed into the API is invoked when its context no longer exists,
    it is generally inappropriate to allow nonlocal control-flow.
    Because it may be invoked from another thread, it is often
    inappropriate to allow such code to access mutable local state.

    &lt;p&gt;The closure proposal attempts to address this category of use
    case by providing the &lt;em&gt;closure conversion&lt;/em&gt;, which converts
    the user-written chunk of code into an anonymous inner class.

    &lt;p&gt;To make this very concrete, let's see how this would affect
    they way you can submit a task to a java.util.concurrent.Executor.
    The way you'd write it today (and this way of writing it will
    always be available) is this:

    &lt;blockquote&gt;

&lt;pre&gt;
void sayHelloInAnotherThread(Executor ex) {
    ex.execute(new Runnable() {
        public void run() {
            System.out.println("hello");
        }
    });
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Now, that's not too bad, but using closures you can write the
    following, without any change to the executor APIs:

    &lt;blockquote&gt;
&lt;pre&gt;
void sayHelloInAnotherThread(Executor ex) {
    ex.execute(() {
        System.out.println("hello");
    });
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;This is a little better, though not necessarily enough by
    itself to justify closures.  This works because although
    &lt;tt&gt;Executor.execute&lt;/tt&gt; takes a &lt;tt&gt;Runnable&lt;/tt&gt; as an
    argument, and we wrote a closure, the &lt;em&gt;closure conversion&lt;/em&gt;

    converts it to a &lt;tt&gt;Runnable&lt;/tt&gt;.  Essentially, the closure
    conversion builds an anonymous instance of &lt;tt&gt;Runnable&lt;/tt&gt; whose
    &lt;tt&gt;run&lt;/tt&gt; method just invokes the closure.  The closure
    conversion is implemented at compile-time, generating exactly the
    same code as in the first case, so there is no runtime overhead.

    &lt;p&gt;If we adopt an alternative invocation syntax that we're working
    on to allow an abbreviated form of invocation statement for
    methods involving closures (we're still working on the
    specification), you would be able to write it something like this:

    &lt;blockquote&gt;
&lt;pre&gt;
void sayHelloInAnotherThread(Executor ex) {
    ex.execute() {
        System.out.println("hello");
    }
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;If this syntax doesn't mean anything to you, just imagine that
    the block appearing at the end of the invocation of
    &lt;tt&gt;ex.execute&lt;/tt&gt; is turned into a closure and then passed as
    the last argment (the only one, in this case) to &lt;tt&gt;execute&lt;/tt&gt;.
    That's basically what the abbreviated invocation syntax does.

    &lt;p&gt;This is a significant improvement compared to what you have to
    write today. You could think of these uses cases as a shorthand
    for creating anonymous class instances.  The analogy isn't exact,
    as certain details necessarily differ to get the langauge
    construct to be well defined.  Most importantly, the binding of
    the names inside the block of code have to be based on the scope
    in which the code appears, which in this case is the method
    &lt;tt&gt;sayHelloInAnotherThread&lt;/tt&gt;, not in the scope of the
    anonymous class that will be created.  Why?  Well, if the meaning
    of a name appearing in a block of code changes when you use it in
    code passed in to method like this, then it would be a fruitful
    source of &lt;a href="http://www.javapuzzlers.com/"&gt;&lt;em&gt;Java
    Programming Puzzles&lt;/em&gt;&lt;/a&gt;.  That is especially true if the
    scope from which the names are inherited isn't even mentioned in
    the code.  It gets worse when you consider that the method name to
    which the closure is being passed might be overloaded, so you
    can't tell when you're typechecking the block which interface you
    are building.

    &lt;p&gt;Some people believe that what you can do with interfaces and
    classes is enough, and would prefer to see no more (and possibly
    less) than some abbreviated syntax for writing anonymous class
    creation expressions.  The most significant difference between
    that approach and closures appears in the other category of use
    cases.

    &lt;h2&gt;Synchronous use cases&lt;/h2&gt;

    &lt;p&gt;The other category I'll call the &lt;em&gt;synchronous&lt;/em&gt; use
    cases, in which the closures you pass to an API element are
    invoked by your own thread strictly before that API element
    returns control to you. There aren't many of these APIs appearing
    in the JDK, usually because such APIs are rather awkward to write.
    Anonymous class instances sometimes satisfy the requirement for
    this category of use cases, and when they don't programmers resort
    to various contortions to get their job done, or simply leave the
    job half done.  Let's see how far we can get, though, using only
    interfaces for this category.  I'll give a single example, again
    motivated by the concurrency framework.

    &lt;p&gt;The Java &lt;tt&gt;synchronized&lt;/tt&gt; statement is convenient and easy
    to use, but for many purposes has been superceded by the
    &lt;tt&gt;Lock&lt;/tt&gt; interface in the concurrency framework.  Here is how
    you currently use a &lt;tt&gt;Lock&lt;/tt&gt; to synchronize a snippet of
    code:

    &lt;blockquote&gt;
&lt;pre&gt;

void sayHelloWhileHoldingLock(Lock lock) {
    lock.lock();
    try {
        System.out.println("hello");
    } finally {
        lock.unlock();
    }
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;This syntax is tedious and distracting.  One would prefer to
    write something like

    &lt;blockquote&gt;
&lt;pre&gt;
void sayHelloWhileHoldingLock(Lock lock) {
    withLock(lock) {
        System.out.println("hello");
    }
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Let's try to write this using only interfaces and classes, and
    perhaps taking advantage of the syntactic abbreviation that we might
    think of as being implemented by translation into inner classes.
    The first thing we'll need is an interface that represents the
    block of code that we're passing in.  &lt;tt&gt;java.lang.Runnable&lt;/tt&gt;

    might just do it.  So our first try at writing this method might
    look something like this:

      &lt;blockquote&gt;
&lt;pre&gt;
void withLock(Lock lock, Runnable runnable) {
    lock.lock();
    try {
        runnable.run();
    } finally {
        lock.unlock();
    }
}
&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;This works for some uses.  It allows us to write the
    &lt;tt&gt;sayHelloWhileHoldingLock&lt;/tt&gt; method, above.  So far so good.
    What happens if we try to write other clients using this?

    &lt;p&gt;Suppose we have the following method that uses old-style locks,
    and we want to refactor it to using a &lt;tt&gt;java.util.concurrent&lt;/tt&gt;

    lock.

      &lt;blockquote&gt;
&lt;pre&gt;
void callBigHonkingWhileHoldingLock(Object lock) throws CheckedException {
    synchronized (lock) {
        bigHonkingMethod(); // throws CheckedException
    }
}&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;The refactored version would presumably look something like this:

      &lt;blockquote&gt;
&lt;pre&gt;
void callBigHonkingWhileHoldingLock(Lock lock) throws CheckedException {
    withLock (lock) {
        bigHonkingMethod(); // throws CheckedException
    }
}&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;It would be nice if this just worked, but it doesn't quite.
    The reason is that the &lt;tt&gt;run&lt;/tt&gt; method of &lt;tt&gt;Runnable&lt;/tt&gt;
    isn't declared to throw any exception types, and specifically it
    doesn't throw &lt;tt&gt;CheckedException&lt;/tt&gt;.  If we make something
    almost like Runnable but in which the &lt;tt&gt;run&lt;/tt&gt; method throws
    &lt;tt&gt;Exception&lt;/tt&gt;, that doesn't quite work either because the
    implementation of &lt;tt&gt;withLock&lt;/tt&gt; would have to declare that it
    throws &lt;tt&gt;Exception&lt;/tt&gt; too, and we aren't catching it in
    &lt;tt&gt;callBigHonkingWhileHoldingLock&lt;/tt&gt;.

    &lt;p&gt;The immediate problem is that the &lt;tt&gt;withLock&lt;/tt&gt; method
    doesn't provide &lt;em&gt;exception transparency&lt;/em&gt;, which means that
    the method throws the same exception type as the method passed in
    to it.  In order to get that, we'd have to make a version of
    &lt;tt&gt;Runnable&lt;/tt&gt; that can also throw some unspecified exception
    type.  We can do that with generics:

      &lt;blockquote&gt;

&lt;pre&gt;
class RunnableWithException&amp;lt;E extends Exception&amp;gt; {
    public void run() throws E;
}
&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;now we can make the &lt;tt&gt;withLock&lt;/tt&gt; method exception-transparent:

      &lt;blockquote&gt;
&lt;pre&gt;
&amp;lt;E&amp;gt; void withLock(Lock lock, RunnableWithException&amp;lt;E&amp;gt; runnable) throws E {
    lock.lock();
    try {
        runnable.run();
    } finally {
        lock.unlock();
    }
}&lt;/pre&gt;

      &lt;/blockquote&gt;

    &lt;p&gt;Assuming the closure conversion can automatically figure out
    that it should be creating an instance of
    &lt;tt&gt;RunnableWithException&amp;lt;CheckedException&amp;gt;&lt;/tt&gt;, which it
    should, this works just fine.

    &lt;p&gt;Things are a bit more complicated when the thing you're running
    can throw two checked exception types; you really want to write a
    version of withLock that doesn't care how many exceptions are
    thrown in the block, they are all just propogated out.  Let's take
    it as a given that the generic type system can be extended to do
    that (I don't think it's too difficult).  Now we have a version of
    &lt;tt&gt;withLock&lt;/tt&gt; that is completely exception-transparent, and
    can be invoked on a block of code that throws any set of exception
    types, which will have to be declared or caught by the caller of
    &lt;tt&gt;withLock&lt;/tt&gt;.  So far so good.

    &lt;p&gt;Let's take another slightly more complex example of a method
    that we might want to refactor to use the new locks:

      &lt;blockquote&gt;
&lt;pre&gt;

boolean containsFred(Object lock, List&amp;lt;String&amp;gt; c) throws CheckedException {
    synchronized (lock) {
        for (String s : c) {
            if (s.toLowerCase().equals("fred")) return true;
        }
    }
    return false;
}&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;The refactored version would presumably look something like this:

      &lt;blockquote&gt;
&lt;pre&gt;
boolean containsFred(lock lock, List&amp;lt;String&amp;gt; c) throws CheckedException {
    withLock (lock) {
        for (String s : c) {
            if (s.toLowerCase().equals("fred")) return true;
        }
        return false;
    }
}&lt;/pre&gt;

      &lt;/blockquote&gt;

    &lt;p&gt;But this won't compile.  The first problem is that the variable
    &lt;tt&gt;c&lt;/tt&gt; isn't final, but it is being accessed within an inner
    class.  We can easily fix that in this case by making &lt;tt&gt;c&lt;/tt&gt;
    final because the variable isn't assigned anywhere.  If the
    variable were assigned somewhere (but not in the block), we could
    create a final local variable to hold a copy of the variable's
    value where it is used, and use that other variable inside the
    block.

    &lt;p&gt;There is a worse problem: the &lt;tt&gt;return true&lt;/tt&gt; statement
    inside the block is returning from the
    &lt;tt&gt;RunnableWithException.run&lt;/tt&gt; method, not
    &lt;tt&gt;containsFred&lt;/tt&gt; but the &lt;tt&gt;run&lt;/tt&gt; method returns
    &lt;tt&gt;void&lt;/tt&gt;.  We could solve that, perhaps, by making a new
    version of &lt;tt&gt;Runnable&lt;/tt&gt;-like interface that returns a
    &lt;tt&gt;boolean&lt;/tt&gt;.  Or better yet perhaps we could add another generic
    type parameter to indicate the return type of the interface's
    method, and have the &lt;tt&gt;withLock&lt;/tt&gt; method return the value to
    its caller that was returned by the block.

    &lt;p&gt;So far so good... well, not quite as good as one would hope,
    because the refactoring isn't straightforward and requires serious
    thought from the programmer. Did you notice that the final &lt;tt&gt;return&lt;/tt&gt;
    statement had to move inside the block?
    But Java programmers generally
    speaking are smart people, and they can work out how to do this.
    I'm sure they enjoy (as much as I do) spending their time puzzling
    out how to coerce the language into doing what they want.

    &lt;p&gt;Next let's try to refactor the following method to use new locks:

      &lt;blockquote&gt;

&lt;pre&gt;
int countBeforeFred(Object lock, List&amp;lt;String&amp;gt; c) throws CheckedException {
    synchronized (lock) {
        int count = 0;
        for (String s : c) {
            if (s.toLowerCase().equals("fred")) return count;
            count++;
        }
    }
    reportMissingFred(c);
}&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;Performing a straightforward refactoring of this code to use a
    method like &lt;tt&gt;withLock&lt;/tt&gt; runs into a number of problems.
    Let's look at the snippet of code that would become the body of
    the method &lt;tt&gt;RunnableWithExceptionAndReturn.run&lt;/tt&gt;

    &lt;blockquote&gt;
&lt;pre&gt;
{
    int count = 0;
    for (String s : c) {
        if (s.toLowerCase().equals("fred")) return count;
        count++;
    }
}&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;This can't possibly be the body of any method: it returns a
    value in the middle of a loop, but it also falls off the end of
    its execution.  In order to refactor this method to use something
    like &lt;tt&gt;withLock&lt;/tt&gt;, we have to start reorganizing the code to
    avoid these problems.  We could move &lt;tt&gt;reportMissingFred(c);&lt;/tt&gt;
    into the synchronized block, but that changes the behavior of the
    program. Another idea is to use a boolean state
    value that is returned to the caller in addition to the count, to
    tell the caller whether or not the block fell off the end, but
    where would we put it?  We can't make it a local variable in
    &lt;tt&gt;countBeforeFred&lt;/tt&gt; because the block can only use final
    variables.  Perhaps we could use a &lt;tt&gt;ThreadLocal&lt;/tt&gt;.  We could
    put a length-one final boolean array in the local scope of
    &lt;tt&gt;countBeforeFred&lt;/tt&gt;, and keep the boolean value in element
    zero.

    &lt;p&gt;If the body of the &lt;tt&gt;countBeforeFred&lt;/tt&gt; were much more
    complicated in its control structure at all, for example
    containing a break from inside the block to outside it, this kind
    of refactoring might become prohibitively complex.  Realistically,
    we would just give up and stop trying to use &lt;tt&gt;withLock&lt;/tt&gt; at
    all, effectively inling it.  After all, it is only a few lines of
    locking code, and it's an idiom that programmers should be
    expected to learn, right?  The idiom is even documented in the
    javadoc of the &lt;tt&gt;Lock&lt;/tt&gt; interface.

    &lt;p&gt;We've only touched the surface, though.  The method
    &lt;tt&gt;withLock&lt;/tt&gt; is perhaps simple enough that you won't mind
    having to inline it except in the simplest of circumstances when
    it does you the least good.  You might feel some discomfort at
    repeating code, especially such boilerplate code, but there really
    isn't any good alternative, and after all it really isn't that
    much code.

    &lt;p&gt;However, some synchronous APIs are naturally more complex, and
    it doesn't take much more complexity in the API before it simply
    doesn't make sense for the caller to repeat code from the
    implementation of the API to avoid these problems.  Consider, for
    example, an API that automatically closes your streams for you.
    Instead of writing

      &lt;blockquote&gt;
&lt;pre&gt;
{
    Stream s = null;
    try {
        s = openStream();
        yourCodeHere();
    } finally {
        try {
            if (s != null) s.close();
        } catch (IOException ex) {}
    }
}&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;You would write an invocation of a library method &lt;tt&gt;closeAtEnd&lt;/tt&gt; to
    get the same effect:

      &lt;blockquote&gt;
&lt;pre&gt;
{
    closeAtEnd(Stream s : openStream()) {
        yourCodeHere();
    }
}
&lt;/pre&gt;
      &lt;/blockquote&gt;

    &lt;p&gt;You would probably go to much greater lengths to avoid inlining
    the API method &lt;tt&gt;closeAtEnd&lt;/tt&gt; than &lt;tt&gt;withLock&lt;/tt&gt;, but the
    same problems are are unavoidable.  These are just two specific
    examples of particular APIs of the synchronous closure variety; if
    the API implementation is much more complicated, or contains
    details in its implementation that callers should not be aware of,
    the problem becomes acute because by-hand inlining is no longer an
    option.  If you've ever used
    &lt;tt&gt;java.security.AccessController.doPrivileged&lt;/tt&gt;, for example,
    you know the pain.

    &lt;p&gt;While we've shown how to achieve exception transparency, we
    haven't quite achieved &lt;em&gt;control transparency&lt;/em&gt;, which means
    that control constructs like &lt;tt&gt;break&lt;/tt&gt;, &lt;tt&gt;continue&lt;/tt&gt;,
    and &lt;tt&gt;return&lt;/tt&gt; have the same meaning when enclosed by a
    closure.  The idea is that you should be able to wrap a block of
    code in an invocation of &lt;tt&gt;withLock&lt;/tt&gt;, &lt;tt&gt;closeAtEnd&lt;/tt&gt;,
    or any other API that takes a block of code, and the meaning of
    the control constructs appearing in that code should be the same.
    Ideally, the only difference is that the block is executed while a
    lock is held, or a stream is closed after the block, or more
    generally whatever is specified and implemented by the API. You
    should be able to &lt;tt&gt;break&lt;/tt&gt; from the block to get out of a
    loop or switch statement that might enclose the invocation of
    &lt;tt&gt;withLock&lt;/tt&gt; or &lt;tt&gt;closeAtEnd&lt;/tt&gt;.  We've looked at
    examples where &lt;tt&gt;return&lt;/tt&gt; is problematic, but the same
    problems occur for other control constructs.  Similarly, and for
    the same reasons, in synchronous APIs you want to be able to refer
    to and modify local variables in the enclosing scope; because the
    block is executed synchronously and by the same thread, there are
    no more concurrency issues than there are for an ordinary block
    statement.

    &lt;p&gt;If you believe that these two methods - &lt;tt&gt;closeAtEnd&lt;/tt&gt; and
    &lt;tt&gt;withLock&lt;/tt&gt; - are the only synchronous APIs worth having,
    now or ever, you might be tempted to add some very specific
    language features to Java to get precisely the desired
    functionality, and dismiss the rest of our closure proposal.  We
    believe that would be a mistake, because we believe that
    synchronous closures would greatly simplify the lives of
    programmers.  There are not many APIs of this sort today, mainly
    because they can't be made to work very well with the language in
    its current state.

    &lt;p&gt;The problem to be solved for synchronous closures is that the
    programmer should not have to transform or contort his code at all
    in order to wrap it in a closure to pass it to one of these APIs.

    &lt;h2&gt;Bridging the Chasm&lt;/h2&gt;

    &lt;p&gt;We're left with two seemingly irreconcilable sets of
    requirements.  Asynchronous closures should not be allowed to
    refer to local variables in the enclosing scope, do not support
    nonlocal control-flow, do not require exception transparency, and
    generally speaking are done today using interfaces or abstract
    classes.  Synchronous closures, on the other hand, should be
    allowed to refer to locals in enclosing scopes, should support
    nonlocal control-flow, and may require exception transparency, but
    generally speaking don't appear in the Java APIs because they are
    not expressible.  These use cases would seem to have so little in
    common that one might not expect a single language construct to
    satisfy both sets of requirements.  But we believe a small
    modification to the currently published proposal, in addition to the
    change described in my previous blog post, satisfies both
    sets of requirements.  This is a very tidy result, because having
    a single uniform language feature is very much preferable to
    having two.

    &lt;p&gt;The change is very simple, but the change is not to the
    specification of function types or closure expressions, it is to
    the specification of the &lt;em&gt;closure conversion&lt;/em&gt;, which allows
    you to write a closure - a block of code - where a one-method
    interface is expected.  We add the additional restrictions that a
    closure to which the closure conversion is applied must not
    reference any non-final local variables from enclosing scopes, and must not use
    &lt;tt&gt;break&lt;/tt&gt;, &lt;tt&gt;continue&lt;/tt&gt;, or &lt;tt&gt;return&lt;/tt&gt; to transfer
    control out of the closure, or the program is in error.  These are the same
    restrictions you have now with anonymous inner classes.

    &lt;p&gt;How does this solve both sets of problems?  Well, first
    consider the asynchronous use cases.  These are expressed using
    interfaces, and therefore in order to use these APIs with the
    closure syntax, the block must be subjected to the closure
    conversion.  Consequently, if there is any use of a nonlocal
    non-final variable, the compiler must reject the program.
    Similarly, the compiler must reject the program if there is
    nonlocal control-flow.  The things that you will be able to do are
    essentially the same as what you can do today, but with a much
    simpler syntax and clearer semantics.

    &lt;p&gt;However, APIs for the synchronous use cases have largely not
    been written yet, so they can be written using the new function
    types. A closure &lt;em&gt;is&lt;/em&gt; an expression of function type, so
    the closure conversion is not required, and its restrictions do
    not apply. Consequently, the block is allowed to use nonlocal
    non-final variables, and can use nonlocal control-flow.  The block
    has essentially the same meaning as it would if it were not
    wrapped by a closure.  In the rare cases that an existing API is
    expressed using an interface but is a synchronous use case - for
    example &lt;tt&gt;java.security.PrivilegedExceptionAction&lt;/tt&gt; - the
    library writer can write a small utility method that converts a
    closure to an implementation of the interface, enabling the client
    to take advantage of the full generality of the feature.
    To implement &lt;tt&gt;withLock&lt;/tt&gt; using closures, with full exception- and
    control-transparency, the JDK authors could write this:

    &lt;blockquote&gt;

&lt;pre&gt;
&amp;lt;E extrends Exception&amp;gt;
public static void withLock(Lock lock, void()throws E block) throws E {
    lock.lock();
    try {
        block();
    } finally {
        lock.unlock();
    }
}
&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;The method &lt;tt&gt;closeAtEnd&lt;/tt&gt; is similarly straightforward.

    &lt;p&gt;Once you have support for synchronous closures, however, there
    are many opportunities for the addition of extremely useful APIs
    to the JDK as library methods, such as &lt;tt&gt;withLock&lt;/tt&gt;,
    &lt;tt&gt;closeAtEnd&lt;/tt&gt;, and a method that simplifies the use of
    &lt;tt&gt;java.security.AccessController.doPrivileged&lt;/tt&gt;.  More
    importantly, synchronous closures enable Java programmers - not
    the JDK authors, but ordinary Java programmers - to freely refactor
    and abstract over pieces of their code in simple ways that are not
    currently possible for seemingly arbitrary reasons.

    &lt;h2&gt;Refactoring&lt;/h2&gt;

    &lt;p&gt;This isn't just about writing and reading programs, it is about
    refactoring programs too. Your ability to factor common code by
    moving it into a separate "routine" is currently limited by how
    the block passed by the caller can interact with the
    caller. Closures, and synchronous closures in particular, simply
    remove that limit. When a program is in need of a small
    refactoring, you are free to factor just the code in common,
    rather than revisiting the design of the basic data structures and
    organization of your application. That was the point of my post &lt;a
    href="http://gafter.blogspot.com/2006/08/whats-point-of-closures.html"&gt;&lt;em&gt;What's
    the Point of Closures&lt;/em&gt;&lt;/a&gt;.  Some people missed the point, and
    thought the program was merely flawed from the beginning and
    should have been rewritten.  Yes, it was flawed, as are most
    programs in the real world. Not every programmer can get
    everything right the first time, or can rewrite thousands of lines
    to solve a localized issue. The whole point of such examples of
    refactoring is that the original program &lt;em&gt;is flawed in some
    way&lt;/em&gt;. If the program were not flawed then refactoring might
    not be required. The refactorings supported by closures enable the
    programmer to get everything right in the end by small refinements
    to the program, step by step.

    &lt;h2&gt;And more...&lt;/h2&gt;

    &lt;p&gt;I believe that the additional expressiveness of the language
    with closures will enable people to discover and use new and
    powerful kinds of design patterns to organize their code in ways
    not possible today, making things simple that currently seem
    complex.  I have some more ideas in this direction, which I'll
    write about at another time when I've had more sleep.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115653428620891109?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115653428620891109' title='33 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115653428620891109'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115653428620891109'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/08/use-cases-for-closures.html' title='Use cases for closures'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>33</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115634662255767882</id><published>2006-08-23T08:22:00.000-07:00</published><updated>2006-10-13T10:42:10.835-07:00</updated><title type='text'>Tennent's Correspondence Principle and Returning From a Closure</title><content type='html'>&lt;p&gt;I just had a very productive meeting with coauthors
    of the closure proposal.  I think we made a lot of progress
    addressing most of the specific concerns people have with the
    proposal (with the exception of subjective comments like "I don't
    think you should do this kind of thing to Java").&lt;/p&gt;

    &lt;p&gt;One issue in particular has been nagging us, and in spite of
    Gilad's insistence that we comply with &lt;em&gt;Tennent's
    Correspondence and Abstraction Principles&lt;/em&gt; (described in
    detail in the now out-of-print book &lt;em&gt;Principles of Programming
    Languages&lt;/em&gt; by R.D.Tennent), Gilad reluctantly admitted before
    we published the first draft that there doesn't seem to be a way
    of doing that for returning from a closure without introducing
    inconsistencies with the rest of the language.  In the end we
    discovered that there is indeed a way to do it, and it seems to be
    rather cleaner than any of the alternatives.&lt;/p&gt;

    &lt;p&gt;Setting aside the technical details of Tennent's approach,
    the principle applies directly to the closure construct.  A
    closure can be used to abstract over an expression or a
    statement.  The principle dictates that an expression or
    statement, when wrapped in a closure and then immediately invoked,
    ought to have the same meaning as it did before being wrapped in a
    closure.  Any change in semantics when wrapping code in a closure
    is likely a flaw in the language.&lt;/p&gt;

    &lt;p&gt;To put this more concretely, an expression
      &lt;blockquote&gt;&lt;em&gt;expr&lt;/em&gt;&lt;/blockquote&gt;

    &lt;p&gt;should have the same meaning as the expression that wraps it in a closure and then evaluates it:
      &lt;blockquote&gt;&lt;tt&gt;(():&lt;/tt&gt;&lt;em&gt;expr&lt;/em&gt;&lt;tt&gt;}()&lt;/tt&gt;&lt;/blockquote&gt;
    &lt;p&gt;And a block statement
      &lt;blockquote&gt;&lt;tt&gt;{ stmt; ... }&lt;/tt&gt;&lt;/blockquote&gt;
    &lt;p&gt;ought to have the same meaning as creating and invoking a closure that wraps the statement:
      &lt;blockquote&gt;&lt;tt&gt;((){ stmt; ... })()&lt;/tt&gt;&lt;/blockquote&gt;

    &lt;p&gt;Tennent's principles are very powerful because violations of
    them tend to show up in the language as flaws, irregularities,
    unnecessary restrictions, unexpected interactions or
    complications, and so on.  While exploring the language design
    space for closures, every time we were tempted to violate them we
    found that there were very real and unpleasant consequences; they
    are very powerful tools for detecting bad smells in a programming
    language design.  The principles apply no less when extending an
    existing programming language, because what you are doing in that
    case is designing the next version of a language.  We discovered
    that when a bad smell is detected by these principles, it is often
    straightforward to illustrate specific problems.  The problems we
    identified also arise in many supposedly "simpler" proposals that
    attempt to provide merely a shorthand notation for construcing
    anonymous class instances.  I'll show two specific issues that we
    identified based on bad smells, examples of the real problems
    caused, and how we solved them.&lt;/p&gt;

    &lt;h2&gt;The meaning of &lt;tt&gt;this&lt;/tt&gt;&lt;/h2&gt;

    &lt;p&gt;Before we look at the question of how to return from a closure,
    and to help understand how the principles are applied, let's look
    at the application of Tennent's principles to the question of the
    meaning of &lt;tt&gt;this&lt;/tt&gt; within a closure.  One possibility would
    be that it designates the closure object itself.  That might be
    useful if you want to define a recursive closure, as you now have
    a convenient way of invoking yourself.  An alternative is that it
    designates the anonymous class instance that is created if the
    &lt;em&gt;closure conversion&lt;/em&gt; is applied.  That seems natural if you
    like to think of the closure expression as a shorthand for
    creating an anonymous class.&lt;/p&gt;

    &lt;p&gt;Unfortunately, both of these alternatives get you into trouble,
    and we can show specific ways that the language no longer fits
    together when you take these approaches.  The former approach, for
    example, doesn't allow you to analyze the types of expressions
    appearing within the closure, because the closure type depends on
    the type of the returned expression, but the returned expression
    might use "this", and so may depend on the type of the closure.
    The latter approach has a similar chicken-and-egg problem, because
    the type of interface you're creating may depend on the types
    within the closure, but the types within the closure depend on the
    type of the interface you're creating.&lt;/p&gt;

    &lt;p&gt;To see the problem more
    simply, one issue is that the expression &lt;tt&gt;this&lt;/tt&gt; no longer
    designates the same thing when wrapped by a closure.  In order to
    abstract (i.e., wrap a closure around) a piece of code that uses
    &lt;tt&gt;this&lt;/tt&gt; or uses any names that are inherited from Object,
    you would have to systematically rewrite those names to qualify
    them in some way to ensure that they refer to the appropriate
    object.  In other words, you'd have to change every &lt;tt&gt;this&lt;/tt&gt;
    to &lt;tt&gt;EnclosingClassName.this&lt;/tt&gt; and every
    &lt;tt&gt;toString()&lt;/tt&gt; to
    &lt;tt&gt;EnclosingClassName.this.toString()&lt;/tt&gt;.  To be most useful as
    an abstraction facility, programmers should be free to wrap a
    piece of code in a closure without worrying that its semantics
    will change subtly.  To satisfy Tennent's Correspondence Principle, a
    closure should introduce into the scope of the closure no names
    that are not explicitly declared by the user - that is, only the
    closure's parameters.&lt;/p&gt;

    &lt;h2&gt;Returning from a closure&lt;/h2&gt;

    &lt;p&gt;The principle also applies to the problem of returning from a
    closure.  The current draft proposal suggests that we use the
    existing &lt;tt&gt;return&lt;/tt&gt; syntax for returning from a closure, but
    that violates the principles; you can detect the bad smell by
    observing that this statement&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;tt&gt;{ if (...) return; }&lt;/tt&gt;

    &lt;/blockquote&gt;

    &lt;p&gt;doesn't mean the same thing as this:

    &lt;blockquote&gt;
      &lt;tt&gt;(){ if (...) return; } ()&lt;/tt&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;The former returns to the enclosing method (not shown), while
    the latter returns from the closure, effectively doing
    nothing.&lt;/p&gt;

    &lt;p&gt;One idea, desribed in the further ideas section of the draft
    spec, is to introduce a new syntax for returning from a closure,
    and reserve the &lt;tt&gt;return&lt;/tt&gt; statement for returning from a
    method, function, or constructor.  We toyed with the statement
    syntax&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;tt&gt;^&lt;/tt&gt; &lt;em&gt;expression&lt;/em&gt;;
    &lt;/blockquote&gt;

    &lt;p&gt;Setting aside aesthetics, this seems to satisfy the
    requirements, because this isn't legal syntax outside a closure.
    Existing code does not have statements of this form, so wrapping
    such code could not change its meaning. However, on further
    reflection we realized that this syntax and all of the other new
    kinds of return statements that we considered have the same flaw
    as using &lt;tt&gt;return&lt;/tt&gt;: while &lt;em&gt;existing&lt;/em&gt; code doesn't use
    this new statement form, once we introduce it into the language we
    should expect people to start using it in &lt;em&gt;new&lt;/em&gt; code.  And
    once they do, any code that includes this statement cannot be
    wrapped in a closure without changing its meaning.  Once we
    identified the bad smell this way, it wasn't hard to come up with
    realistic examples where it gets in the way of using the
    language.&lt;/p&gt;

    &lt;p&gt;Having eliminated any form of return statement, what are you
    left with?  Referring back to Tennent's principles is instructive:
    you should be able to replace an expression &lt;em&gt;expr&lt;/em&gt; with&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;tt&gt;(){&lt;/tt&gt; &lt;em&gt;expr&lt;/em&gt; &lt;tt&gt;} ()&lt;/tt&gt;

    &lt;/blockquote&gt;

    &lt;p&gt;This is the proposed syntax for returning a value from a
    closure.  It is simpler than the existing spec because no rules
    are needed to infer the return type; it is the type of the
    expression.  Of course, we will want to allow a list of statements
    instead of an expression to allow the construct to close over
    statements (in which case the closure returns &lt;tt&gt;void&lt;/tt&gt;), and
    allow a list of statements to precede a trailing expression (in
    which case the final expression is the result of the closure).  An
    expression without a trailing semicolon isn't a legal statement
    form, so there is no confusion with any existing constructs.  This
    nicely satisfies Tennent's principles.  My only regret is that
    there is no single way to both designate the returned value and
    return from a closure before its end, which would be slightly more
    consistent with Java's existing control constructs.&lt;/p&gt;

    &lt;h2&gt;And more...&lt;/h2&gt;

    &lt;p&gt;We made progress on a number of issues:

    &lt;ul&gt;
      &lt;li&gt;We know how to address concerns about how the closure
      conversion will interact with APIs like concurrency and
      asynchronous notification systems where the closure isn't just
      called by the current thread; in those APIs you don't want to
      allow nonlocal control-flow or capturing nonfinal variables.

      &lt;li&gt;We think we can add support for type inference of exception
      types to allow writing APIs in which the set of exceptions from
      a block (closure) that is passed in to the API can propogate out
      of the API while being strongly type-checked.

      &lt;li&gt;We think it should be possible to write a class that
      "implements" a function type, as suggested by "crazy" Bob Lee,
      so that you can define a custom &lt;tt&gt;toString()&lt;/tt&gt; to make
      debugging easier or make the implementation serializable.

      &lt;li&gt;We started looking at a number of specific use cases that
      have been suggested, such as a library that allows you to
      execute a block of code while holding a
      java.util.concurrent.locks.Lock, unlocking it at the end, or a
      library that closes your streams (or other Closable things)
      after your block of code is finished.

      &lt;li&gt;We've also made progress on detailing the set of
      implementation techniques that might be used to implement the
      facility.
    &lt;/ul&gt;

    &lt;p&gt;I'll blog about these later.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115634662255767882?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115634662255767882' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115634662255767882'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115634662255767882'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/08/tennents-correspondence-principle-and.html' title='Tennent&apos;s Correspondence Principle and Returning From a Closure'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115603556105250694</id><published>2006-08-19T17:50:00.000-07:00</published><updated>2006-10-13T10:42:10.767-07:00</updated><title type='text'>What's the point of Closures?</title><content type='html'>&lt;p&gt;A number of people have asked me: What's the point of closures? Can't
you accomplish pretty much the same thing with the existing language
constructs? What does it really buy you?
&lt;p&gt;If you haven't programmed using closures, and you've gotten used to the
Java idioms for the past ten years, it might be hard to see what closures
really buy you.  This is my attempt to give you a glimpse of that, by
way of an extended example.
&lt;h2&gt;The problem&lt;/h2&gt;
&lt;p&gt;Suppose you are working with an application that maintains a list of
documents, and for each individual in some set a list of document annotations.
For the sake of this example, suppose the two lists are parallel.  That is,
if you take the list of annotations from an individual, the values correspond
elementwise with the elements of the document list.  To make this more
concrete:
&lt;blockquote&gt;&lt;pre&gt;
class Document { ... }
class DocAnnotation { ... }
class Person { ... }
class Documents {
    static List&amp;lt;Document&amp;gt; allDocuments();
}
class Persons {
    static Set&amp;lt;Person&amp;gt; allPersons();
    static Person GEORGE_W_BUSH = ...;
}
class DocAnnotations {
    static Map&amp;lt;Person,List&amp;lt;DocAnnotation&amp;gt;&amp;gt; allAnnotations = ...;
}

&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Now, you might ask a question such as: Has George Bush annotated any
documents mentioning &lt;em&gt;Iraq&lt;/em&gt; as &lt;em&gt;secret&lt;/em&gt;.  In this hypothetical
application, you might code that up something like this:
&lt;blockquote&gt;&lt;pre&gt;
boolean bushMarkedAnyIraqDocsSecret() {
    Iterator&amp;lt;Document&amp;gt; docI = Documents.allDocuments().iterator();
    Iterator&amp;lt;DocAnnotation&amp;gt; annI =
        DocAnnotations.allAnnotations.get(GEORGE_W_BUSH).iterator();
    while (docI.hasNext() &amp;&amp; annI.hasNext()) {
        Document doc = docI.next();
        DocAnnotation docAnn = annI.next();
        if (doc.mentions("Iraq") &amp;&amp; docAnn.marked("secret")) {
            return true;
        }
    }
    return false;
}

&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;We could abstract this over what we're looking for in the
document, who'se annotations we're looking for, and what kind of annotation
we're looking for:
&lt;blockquote&gt;&lt;pre&gt;
boolean personAnnotatedOnKeyword(Person person, String ann, String key) {
    Iterator&amp;lt;Document&amp;gt; docI = Documents.allDocuments().iterator();
    Iterator&amp;lt;DocAnnotation&amp;gt; annI =
        DocAnnotations.allAnnotations.get(person).iterator();
    while (docI.hasNext() &amp;&amp; annI.hasNext()) {
        Document doc = docI.next();
        DocAnnotation docAnn = annI.next();
        if (doc.mentions(key) &amp;&amp; docAnn.marked(ann)) {
            return true;
        }
    }
    return false;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;It is possible that abstracting in this way allowes us to avoid repeating
this loop throughout the code, if the code frequently needs
to ask this kind of
question.  Abstracting common code is good because, among other things,
it allows us to reduce the number of things we need to change
when we refactor
code.  For example, if we were to change the representation of a person's
annotations to be a Map&amp;lt;Document,DocAnnotation&amp;gt;

instead of List&amp;lt;DocAnnotation&amp;gt;, or make a DocAnnotation contain
a reference to the Document,
we would have to change this kind of loop everywhere it
appears.  So
having a single place where the loop is written is a good thing,
as there are fewer places in the code that depend on the exact
representation of the data.
&lt;h2&gt;Abstracting the loop in JDK5&lt;/h2&gt;
&lt;p&gt;The next step is to try to abstract the loop itself.  Java provides some
convenient looping constructs, including the recently introduced for-each
loop with its &lt;tt&gt;Iterable&lt;/tt&gt; interface.  We can use that, but we need to
introduce a type over which we're iterating:
&lt;blockquote&gt;&lt;pre&gt;
class DocAndAnnotation {
    final Document doc;
    final DocAnnotation docAnn;
    DocAndAnnotation(Document doc, DocAnnotation docAnn) {
        this.doc = doc;
        this.docAnn = docAnn;
    }
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Now we can provide looping support by writing the loop only once in the
code like this
&lt;blockquote&gt;&lt;pre&gt;
Collection&amp;lt;DocAndAnnotation&amp;gt; docsWithAnnotations(Person person) {
    Iterator&amp;lt;Document&amp;gt; docI = Documents.allDocuments().iterator();
    Iterator&amp;lt;DocAnnotation&amp;gt; annI =
        DocAnnotations.allAnnotations.get(person).iterator();
    List&amp;lt;DocAndAnnotation&amp;gt; result =
        new ArrayList&amp;lt;DocAndAnnotation&amp;gt;();
    while (docI.hasNext() &amp;&amp; annI.hasNext()) {
        Document doc = docI.next();
        DocAnnotation docAnn = annI.next();
        result.add(new DocAndAnnotation(doc, docAnn));
    }
    return result;
}

&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This allows us to write the original loop like this:
&lt;blockquote&gt;&lt;pre&gt;
boolean personAnnotatedOnKeyword(Person person, String ann, String key) {
    for (DocAndAnnotation docAndAnn : docsWithAnnotations(person)) {
        if (docWithAnn.doc.mentions(key) &amp;&amp; docWithAnn.docAnn.marked(ann)) {
            return true;
        }
    }
    return false;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;So far so good, but this solution has an unfortunate feature: it
constructs the entire list even if the answer can be found by looking at
only the first annotated document.  We can do slightly better by
constructing a lazy iterator instead of an eager list.  We do that by
rewriting &lt;tt&gt;docsWithAnnotations&lt;/tt&gt; as follows:
&lt;blockquote&gt;&lt;pre&gt;
Iterable&amp;lt;DocAndAnnotation&amp;gt; docsWithAnnotations(Person person) {
    final Iterator&amp;lt;Document&amp;gt; docI =
        Documents.allDocuments().iterator();
    final Iterator&amp;lt;DocAnnotation&amp;gt; annI =
        DocAnnotations.allAnnotations.get(person).iterator();
    return new Iterable&amp;lt;DocAndAnnotation&amp;gt;() {
        public Iterator&amp;lt;DocAndAnnotation&amp;gt; iterator() {
            return new Iterator&amp;lt;DocAndAnnotation&amp;gt;() {
                public boolean hasNext() {
                    return docI.hasNext() &amp;&amp; annI.hasNext();
                }
                public DocAndAnnotation next() {
                    return new DocAndAnnotation(docI.next(), annI.next());
                }
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    };
}

&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Now, without changing &lt;tt&gt;personAnnotatedOnKeyword&lt;/tt&gt;, the same
loop works without the
overhead of building the entire List&amp;lt;DocAndAnnotation&amp;gt;.
&lt;p&gt;This program does, however, produce a large number of small, transient
garbage objects.  The Iterator, Iterable, and DocAndAnnotation objects are
all short-lived and simply exist to convey data from one part of the program
to another.  This is not necessarily a problem; HotSpot has a number of
garbage-collection algorithms that are good at allocating and reclaiming
short-lived objects.  But in some applications it could contribute toward
a performance bottleneck.
&lt;p&gt;Can the looping code be refactored to avoid all these small allocations?
The answer is yes, and there is a standard idiom for doing that in Java.
The idea is to turn the control structure of the loop inside-out.
Rather than having the &lt;tt&gt;personAnnotatedOnKeyword&lt;/tt&gt; perform the
iteration, we have a library method perform the iteration and pass the
values to a snippet of code provided by &lt;tt&gt;personAnnotatedOnKeyword&lt;/tt&gt;.
That would look something like this:
&lt;blockquote&gt;&lt;pre&gt;
interface WithDocumentAndAnnotation {
    void doIt(Document doc, DocAnnotation docAnn);
}
void docsWithAnnotations(
        Person person, WithDocumentAndAnnotation body) {
    Iterator&amp;lt;Document&amp;gt; docI = Documents.allDocuments().iterator();
    Iterator&amp;lt;DocAnnotation&amp;gt; annI =
        DocAnnotations.allAnnotations.get(person).iterator();
    while (docI.hasNext() &amp;&amp; annI.hasNext()) {
        Document doc = docI.next();
        DocAnnotation docAnn = annI.next();
        body.doIt(doc, docAnn);
    }
}

&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;A client can now iterate through a person's annotations by providing
a snippet of code in the form of a class that implements the
interface:
&lt;blockquote&gt;&lt;pre&gt;
boolean personAnnotatedOnKeyword(
        Person person, final String ann, final String key) {
    class MyBody implements WithDocumentAndAnnotation {
        boolean result = false;
        public void doIt(Document doc, DocAnnotation docAnn) {
            if (doc.mentions(key) &amp;&amp; docAnn.marked(ann)) {
                result = true;
            }
        }
    }
    MyBody body = new MyBody();
    docsWithAnnotations(person, body);
    return body.result;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This solves the transient memory allocation problem (if it even was
a problem), but this version of the program again unnnecessarily iterates
through all of the documents even if it needs to iterate through only a few
to compute its result.  We can fix that by modifying the
&lt;tt&gt;WithDocumentAndAnnotation&lt;/tt&gt; interface's method to return a
&lt;tt&gt;boolean&lt;/tt&gt;, which indicates whether or not iteration should continue
or whether the loop should abort.  This may enable many of the old clients
of the &lt;tt&gt;docsWithAnnotations&lt;/tt&gt; method to migrate to the new API, but
it may not satisfy the needs of all of them.  Presumably we could modify
the interface further as we discovered different patterns of control-flow
used by clients that iterate through documents and their annotations.
We leave the details as an exercise to the reader.
&lt;h2&gt;Abstracting the loop with Closures&lt;/h2&gt;

&lt;p&gt;Closures provide a somewhat more convenient way to abstract the loop:
&lt;blockquote&gt;&lt;pre&gt;
void docsWithAnnotations(Person person, void(Document,DocAnnotation) block) {
    Iterator&amp;lt;Document&amp;gt; docI = Documents.allDocuments().iterator();
    Iterator&amp;lt;DocAnnotation&amp;gt; annI =
        DocAnnotations.allAnnotations.get(person).iterator();
    while (docI.hasNext() &amp;&amp; annI.hasNext()) {
        Document doc = docI.next();
        DocAnnotation docAnn = annI.next();
        block(doc, docAnn);
    }
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This looks almost the same as our last version using JDK5, except that it
does not require the introduction of
the &lt;tt&gt;WithDocumentAndAnnotation&lt;/tt&gt; interface.
Let's see what the client looks like:
&lt;blockquote&gt;&lt;pre&gt;

boolean personAnnotatedOnKeyword(
        Person person, final String ann, final String key) {
    docsWithAnnotations(person, (Document doc, DocAnnotation docAnn) {
        if (doc.mentions(key) &amp;&amp; docAnn.marked(ann)) {
            return personAnnotatedOnKeyword: true;
        }
    });
    return false;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;That's it.  If we adopt the modifications to the proposal suggested in the
&lt;em&gt;Further Ideas&lt;/em&gt; section, the client would look something like this:
&lt;blockquote&gt;&lt;pre&gt;
boolean personAnnotatedOnKeyword(
        Person person, final String ann, final String key) {
    docsWithAnnotations(person) (Document doc, DocAnnotation docAnn) {
        if (doc.mentions(key) &amp;&amp; docAnn.marked(ann)) {
            return true;
        }
    }
    return false;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;The only transient objects created in this version are the closure
object itself and the two iterators used in the implementation of
&lt;tt&gt;docsWithAnnotations&lt;/tt&gt;.  As you can see, the caller of
&lt;tt&gt;docsWithAnnotations&lt;/tt&gt; can use control-flow operations like

&lt;tt&gt;return&lt;/tt&gt; without the implementation of &lt;tt&gt;docsWithAnnotations&lt;/tt&gt;
having to anticipate what kinds of control-flow will be required.
&lt;p&gt;Now, in the interest of full disclosure I should mention that the
&lt;tt&gt;return&lt;/tt&gt; statement within the closure is likely to be implemented
under the covers using exceptions.  That's one more transient object we
should count.  As for the performance of using an exception in this way,
I'm told by HotSpot engineers that an exception used this way
is largely optimized away by the VM if found in performance-critical code.
The most expensive part
of exception handling by far
is capturing the stack trace when creating the
exception, and we would want to create exceptions for this purpose
without stack traces.
&lt;p&gt;That really is it.  All of the design iterations we went through to
handle variations on this problem in JDK5 simply don't arise as issues.
That's the beauty of closures: they allow you to easily
abstract away aspects of code that would otherwise require complex
contortions.
&lt;p&gt;A slight update on my current feelings about the draft spec.  I
think we are likely to drop the special syntax for a nonlocal return,
and have a different syntax for returning from a closure.  This is
hinted at in the &lt;em&gt;Further Ideas&lt;/em&gt; section.  "return" would mean
return from the enclosing method or function, and if you're inside a
closure you would write a statement something like "^ expression;" to
return a value from the closure.  Most value-returning closures are
unlikely to need this syntax, since they can often be expressed using
the "(args) : expression" form.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115603556105250694?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115603556105250694' title='29 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115603556105250694'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115603556105250694'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/08/whats-point-of-closures.html' title='What&apos;s the point of Closures?'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>29</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-115591181028335517</id><published>2006-08-18T07:30:00.000-07:00</published><updated>2008-01-31T09:20:43.143-08:00</updated><title type='text'>Closures for Java</title><content type='html'>&lt;span style="font-style:italic;"&gt;I'm co-author of a draft proposal for adding support for closures to the Java programming language for the Dolphin (JDK 7) release. It was carefully designed to interoperate with the current idiom of one-method interfaces. An abbreviated version of the original proposal is reproduced below. The latest version of the proposal and a prototype can be found at &lt;a href="http://www.javac.info/"&gt;http://www.javac.info/&lt;/a&gt;.&lt;/span&gt;
&lt;p  style='text-align: right;'&gt; &lt;em&gt;Gilad Bracha, Neal Gafter, James Gosling, Peter von der Ahé&lt;/em&gt;
&lt;p&gt;Modern programming languages provide a mixture of primitives for composing programs. C#, Javascript, Ruby, Scala, and Smalltalk (to name just a few) have direct language support for &lt;em&gt;function types&lt;/em&gt; and inline function-valued expression, called &lt;em&gt;closures&lt;/em&gt;. A proposal for closures is working its way through the C++ standards committees as well. Function types provide a natural way to express some kinds of abstraction that are currently quite awkward to express in Java. For programming in the small, closures allow one to abstract an algorithm over a piece of code; that is, they allow one to more easily extract the common parts of two almost-identical pieces of code. For programming in the large, closures support APIs that express an algorithm abstracted over some computational aspect of the algorithm. We propose to add function types and closures to Java.  We anticipate that the additional expressiveness of the language will simplify the use of existing APIs and enable new kinds of APIs that are currently too awkward to express using the best current idiom: interfaces and anonymous classes.
&lt;h2&gt;Function Types&lt;/h2&gt;
&lt;p&gt;We introduce a new syntactic form:
&lt;dl&gt;&lt;dt&gt;&lt;em&gt;Type&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Type&lt;/em&gt; ( &lt;em&gt;TypeList&lt;/em&gt; ) { &lt;code&gt;throws&lt;/code&gt; &lt;em&gt;ThrowsTypeList&lt;/em&gt; }

&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;ThrowsTypeList&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Type&lt;/em&gt;
&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;ThrowsTypeList&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;ThrowsTypeList&lt;/em&gt; VBAR &lt;em&gt;Type&lt;/em&gt;
&lt;/dd&gt;&lt;dt&gt;VBAR&lt;/dt&gt;&lt;dd&gt;|
&lt;/dd&gt;&lt;/dl&gt;
&lt;p&gt;These syntactic forms designate &lt;em&gt;function types&lt;/em&gt;. A function type is a kind of reference type. A function type consists of a return type, a list of argument types, and a set of thrown exception types.
&lt;p style='margin-left: 40px;'&gt;Note: the existing syntax for the throws clause in a method declaration uses a comma to separate elements of the &lt;em&gt;ThrowsTypeList&lt;/em&gt;. For backward compatibility we continue to allow commas to separate these elements in method and function declarations, but in function types we require the use of the '&lt;code&gt;|&lt;/code&gt;' (vertical-bar) character as aseparator to resolve a true ambiguity that would arise when a function type is used in a type list.  For uniformity of syntax, we also allow the vertical-bar as a separator in the throws clause of method and function definitions, and as a matter of style we recommend that new code prefer the vertical-bar.

&lt;h2&gt;Local Functions&lt;/h2&gt;
&lt;p&gt;In addition to function types, we introduce &lt;em&gt;local functions&lt;/em&gt;, which are one way to introduce a name with function type:
&lt;dl&gt;&lt;dt&gt;&lt;em&gt;BlockStatement&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;LocalFunctionDeclarationStatement&lt;/em&gt;
&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;LocalFunctionDeclarationStatement&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Type&lt;/em&gt; &lt;em&gt;Identifier&lt;/em&gt; &lt;em&gt;FormalParameters&lt;/em&gt; { &lt;code&gt;throws&lt;/code&gt; &lt;em&gt;ThrowsTypeList&lt;/em&gt; } &lt;em&gt;Block&lt;/em&gt;

&lt;/dd&gt;&lt;/dl&gt;
&lt;p&gt;A local function declaration has the effect of declaring a final variable of function type.  Local functions may not be declared with a variable argument list.  Local functions may invoke themselves recursively.
&lt;p style='margin-left: 40px;'&gt;Note: this syntax omits annotations, which should be allowed on local functions.
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;Combining these forms, we can write a simple function and assign
it to a local function variable:
&lt;pre&gt; public static void main(String[] args) {
     int plus2(int x) { return x+2; }
     int(int) plus2b = plus2;
     System.out.println(plus2b(2));
 }
&lt;/pre&gt;
&lt;h2&gt;Namespaces and name lookup&lt;/h2&gt;
&lt;p&gt;The Java programming language currently maintains a strict separation between &lt;em&gt;expression names&lt;/em&gt; and &lt;em&gt;method names&lt;/em&gt;. These two separate namespaces allow a programmer to use the same name for a variable and for methods. Local functions and closure variables necessarily blur the distinction between these two namespaces: local functions may be used as expression values; contrariwise, variables of function type may be invoked.

&lt;p&gt;A local function declaration introduces the declared name as a variable name.  When searching a scope for a method name, if no methods exist with the given name then local functions and variables of the given name that are of function type are considered candidates. If more than one exists (for example, function-typed variable declarations are inherited from separate supertypes), the reference is considered ambiguous; local functions do not overload.
&lt;p&gt;When searching a scope for an expression name, local functions are treated as variables. Function names and values can therefore be used like other values in a program, and can be applied using the existing invocation syntax. In addition, we allow a function to be invoked from an arbitrary (for example, parenthesized) expression:
&lt;dl&gt;&lt;dt&gt;&lt;em&gt;Primary&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Primary&lt;/em&gt; &lt;em&gt;Arguments&lt;/em&gt;
&lt;/dd&gt;&lt;/dl&gt;
&lt;h2&gt;Anonymous Functions (Closures)&lt;/h2&gt;
&lt;p&gt;We also introduce a syntactic form for constructing a function value without declaring a local function (precedence is tentative):
&lt;dl&gt;&lt;dt&gt;&lt;em&gt;Expression3&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;Closure&lt;/em&gt;

&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;Closure&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;FormalParameters&lt;/em&gt; &lt;em&gt;Block&lt;/em&gt;

&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;Closure&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;em&gt;FormalParameters&lt;/em&gt; : &lt;em&gt;Expression3&lt;/em&gt;
&lt;/dd&gt;&lt;/dl&gt;
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;We can rewrite the assignment to &lt;code&gt;plus2b&lt;/code&gt; in the previous example using an anonymous function:
&lt;pre&gt;    int(int) plus2b = (int x) {return x+2; };
&lt;/pre&gt;
&lt;p&gt;Or, using the short form,

&lt;pre&gt;    int(int) plus2b = (int x) : x+2;
&lt;/pre&gt;
&lt;h2&gt;The type of a closure&lt;/h2&gt;
&lt;p&gt;The type of a closure is inferred from its form as follows:
&lt;p&gt;The argument types of a closure are the types of the declared arguments.
&lt;p&gt;For the short form of a closure, the return type is the type of the expression following the colon. For a long form of a closure, if the body contains no return statement and the body cannot complete normally, the return type is the type of &lt;code&gt;null&lt;/code&gt;. Otherwise if the body contains no return statement or the form of return statements are without a value, the return type is &lt;code&gt;void&lt;/code&gt;
&lt;p&gt;Otherwise, consider the set of types appearing in the &lt;code&gt;return&lt;/code&gt; statements within the body. These types are combined from left to right using the rules of the &lt;em&gt;conditional operator&lt;/em&gt; (JLS3 15.25) to compute a single unique type, which is the return type of the closure.

&lt;p&gt;The set of thrown types of a closure are those checked exception types thrown by the body.
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;The following illustrates a closure being assigned to a variable with precisely the type of the closure.
&lt;pre&gt;    void(int) throws InterruptedException closure =
  (int t) { Thread.sleep(t); }
&lt;/pre&gt;
&lt;h2&gt;Subtyping&lt;/h2&gt;
&lt;p&gt;A function type &lt;em&gt;T&lt;/em&gt; is a subtype of function type &lt;em&gt;U&lt;/em&gt; iff all of the following hold:
&lt;ul&gt;&lt;li&gt;Either

&lt;ul&gt;&lt;li&gt;The return type of &lt;em&gt;T&lt;/em&gt; is either the same as the return type of &lt;em&gt;U&lt;/em&gt; or
&lt;/li&gt;&lt;li&gt;Both return types are reference types and the return type of &lt;em&gt;T&lt;/em&gt; is a subtype of the return type of &lt;em&gt;U&lt;/em&gt;, or
&lt;/li&gt;&lt;li&gt;the return type of &lt;em&gt;U&lt;/em&gt; is &lt;code&gt;void&lt;/code&gt;.

&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;em&gt;T&lt;/em&gt; and &lt;em&gt;U&lt;/em&gt; have the same number of declared arguments.
&lt;/li&gt;&lt;li&gt;For each corresponding argument position in the argument list of &lt;em&gt;T&lt;/em&gt; and &lt;em&gt;U&lt;/em&gt;, either both argument types are the same or both are reference types and the type of the argument to &lt;em&gt;U&lt;/em&gt; is a subtype of the corresponding argument to &lt;em&gt;T&lt;/em&gt;.

&lt;/li&gt;&lt;li&gt;Every exception type in the throws of &lt;em&gt;T&lt;/em&gt; is a subtype of some exception type in the throws of &lt;em&gt;U&lt;/em&gt;.
&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Exception handling&lt;/h2&gt;
&lt;p&gt;The invocation of a function throws every checked exception type in the function's type.
&lt;p&gt;It is a compile-time error if the body of a function can throw a checked exception type that is not a subtype of some member of the throws clause of the function.
&lt;h2&gt;Reflection&lt;/h2&gt;
&lt;p&gt;A function type inherits all the non-private methods from &lt;code&gt;Object&lt;/code&gt;. The following methods are added to &lt;code&gt;java.lang.Class&lt;/code&gt; to support function types:

&lt;pre&gt;    public final class java.lang.Class&amp;lt;T&amp;gt; ... {
        public boolean isFunction();
        public java.lang.reflect.FunctionType functionType();
        public Object invokeFunction(Object function, Object ... args)
           throws IllegalArgumentException | InvocationTargetException;
    }
    public interface java.lang.reflect.FunctionType {
        public Type returnType();
        public Type[] argumentTypes();
        public Type[] throwsTypes();
    }
&lt;/pre&gt;
&lt;p style='margin-left:40px'&gt;Note: unlike &lt;code&gt;java.lang.reflect.Method.invoke&lt;/code&gt;, &lt;code&gt;Class.invokeFunction&lt;/code&gt; cannot throw &lt;code&gt;IllegalAccessException&lt;/code&gt;, because there is no access control to enforce; the function value designates either an anonymous or local function, neither of which allows access modifiers in its declaration. Access to function values is controlled at compile-time by their &lt;em&gt;scope,&lt;/em&gt; and at runtime by controlling the function value.

&lt;h2&gt;The type of &lt;code&gt;null&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;We add support for &lt;code&gt;null&lt;/code&gt; and the type of &lt;code&gt;null&lt;/code&gt; in function types.  We introduce a meaning for the keyword &lt;code&gt;null&lt;/code&gt; as a type name; it designates the type of the expression &lt;code&gt;null&lt;/code&gt;. A class literal for the type of &lt;code&gt;null&lt;/code&gt; is &lt;code&gt;null.class&lt;/code&gt;.  These are necessary to allow reflection, type inference, and closure literals to work for functions that do not return normally. We also add the non-instantiable class &lt;code&gt;java.lang.Null&lt;/code&gt; as a placeholder, and its static member field &lt;code&gt;TYPE&lt;/code&gt; as a synonym for &lt;code&gt;null.class&lt;/code&gt;.

&lt;h2&gt;Referencing names from the enclosing scope&lt;/h2&gt;
&lt;p&gt;Names that are in scope where a function or closure is defined may be referenced within the closure. We do not propose a rule that requires referenced variables be final, as is currently required for anonymous class instances. The constraint on anonymous class instances is also relaxed to allow them to reference any local variable in scope.
&lt;p style='margin-left:40px'&gt;Note: Some who see concurrency constructs being the closure construct's primary use prefer to either require such referenced variables be final, or that such variables be explicitly declared for sharing, perhaps by requiring them be declared volatile. We reject this proposal for a few reasons. First, concurrency has no special role in the need for closures in the Java programming language; the proposal punishes other users of the feature for the convenience of these few.  Second, the proposal is non-parallel with the closest existing parallel structure: classes. There is no constraint that a method may only access, for example, volatile fields of itself or other objects or enclosing classes. If compatibility allowed us to add such a rule to Java at this time, such a rule would obviously inconvenience most programmers for very little benefit. Third, marking such variables volatile, with all the semantic meaning implied by volatile, is neither necessary nor sufficient to ensure (and hardly assists!) appropriate use in a multithreaded environment.
&lt;h2&gt;Non-local transfer&lt;/h2&gt;
&lt;p&gt;One purpose for closures is to allow a programmer to refactor common code into a shared utility, with the difference between the use sites being abstracted into a local function or closure. The code to be abstracted sometimes contains a &lt;code&gt;break&lt;/code&gt;, &lt;code&gt;continue&lt;/code&gt;, or &lt;code&gt;return&lt;/code&gt; statement. This need not be an obstacle to the transformation. A &lt;code&gt;break&lt;/code&gt; or &lt;code&gt;continue&lt;/code&gt; statement appearing within a closure or local function may transfer to any matching enclosing statement provided the target of the transfer is in the same innermost &lt;em&gt;ClassBody&lt;/em&gt;.

&lt;p&gt;Because the &lt;code&gt;return&lt;/code&gt; statement within a block of code is given new meaning when transformed by being surrounded by a closure, a different syntactic construct is required to return from an enclosing function or method. The following new form of the &lt;code&gt;return&lt;/code&gt; statement may be used within a closure or local function to return from any enclosing (named) local function or method, provided the target of the transfer is in the same innermost &lt;em&gt;&lt;span class='wikiword'&gt;ClassBody&lt;/span&gt;&lt;/em&gt;:
&lt;dl&gt;&lt;dt&gt;&lt;em&gt;NamedReturnStatement&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;code&gt;return&lt;/code&gt; &lt;em&gt;Identifier&lt;/em&gt; : ;
&lt;/dd&gt;&lt;dt&gt;&lt;em&gt;NamedReturnStatement&lt;/em&gt;&lt;/dt&gt;&lt;dd&gt;&lt;code&gt;return&lt;/code&gt; &lt;em&gt;Identifier&lt;/em&gt; : &lt;em&gt;Expression&lt;/em&gt; ;

&lt;/dd&gt;&lt;/dl&gt;
&lt;p&gt;No syntax is provided to return from a lexically enclosing closure. If such non-local return is required, the code should be rewritten using a local function (i.e. introducing a name) in place of the closure.
&lt;p&gt;If a &lt;code&gt;break&lt;/code&gt; statement is executed that would transfer control out of a statement that is no longer executing, or is executing in another thread, the VM throws a new unchecked exception, &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt;. (I suspect we can come up with a better name). Similarly, an &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt; is thrown when a &lt;code&gt;continue&lt;/code&gt; statement attempts to complete a loop iteration that is not executing in the current thread. Finally, an &lt;code&gt;UnmatchedNonlocalTransfer&lt;/code&gt; is thrown when a &lt;em&gt;NamedReturnStatement&lt;/em&gt; attempts to return from a function or method invocation that is not pending in the current thread.

&lt;h2&gt;Closure conversion&lt;/h2&gt;
&lt;p&gt;We propose the following closure conversion, to be applied only in those contexts where boxing currently occurs:
&lt;p style='margin-left:40px'&gt;There is a &lt;em&gt;closure conversion&lt;/em&gt; from every closure of type T to every interface type that has a single method with signature U such that T is a subtype of the function type corresponding to U.
&lt;p&gt;We will want to generalize this rule slightly to allow the conversion when boxing or unboxing of the return type is required, e.g. to allow assigning a closure that returns &lt;code&gt;int&lt;/code&gt; to an interface whose method returns &lt;code&gt;Integer&lt;/code&gt; or vice versa.
&lt;p style='margin-left:40px'&gt;Note: The current Java idiom for capturing a snippet of code requires the use of a one-method interface to represent the function type and an anonymous class instance to represent the closure:
&lt;pre&gt;        public interface Runnable {
           void run();
        }
        public interface API {
           void doRun(Runnable runnable);
        }
        public class Client {
            void doit(API api) {
                api.doRun(new Runnable(){
                   public void run() {
                       snippetOfCode();
                   }
                });
            }
        }

&lt;/pre&gt;
&lt;p style='margin-left:40px'&gt;Had function types been available when this API was written, it might have been written like this:
&lt;pre&gt;        public interface API {
            void doRun(void() func);
        }

&lt;/pre&gt;
&lt;p style='margin-left:40px'&gt;And the client like this:
&lt;pre&gt;        public class Client {
            void doit(API api) {
                api.doRun(() {snippetOfCode(); });
            }
        }
&lt;/pre&gt;
&lt;p style='margin-left:40px'&gt;Unfortunately, compatibility prevents us from changing existing APIs. One possibility is to introduce a boxing utility method somewhere in the libraries:
&lt;pre&gt;        Runnable runnable(final void() func) {
            return new Runnable() {
                public void run() { func(); }
            };
        }
&lt;/pre&gt;
&lt;p style='margin-left:40px'&gt;Allowing the client to write this:
&lt;pre&gt;        public class Client {
            void doit(API api) {
                api.doRun(runnable(() {snippetOfCode(); }));
            }
        }
&lt;/pre&gt;

&lt;p style='margin-left:40px'&gt;This may be nearly good enough from the point of view of how concise the usage is, but it has one more serious drawback: every creation of a Runnable this way requires that two objects be allocated instead of one (one for the closure and one for the Runnable), and every invocation of a method constructed this way requires an extra invocation. For some applications -- for example, micro-concurrency -- this overhead may be too high to allow the use of the closure syntax with existing APIs. Moreover, the VM-level optimizations required to generate adequate code for this kind of construct are difficult and unlikely to be widely implemented soon.
&lt;p style='margin-left:40px'&gt;The closure conversion is applied only to closures (i.e. function literals), not to arbitrary expressions of function type. This enables javac to allocate only one object, rather than both a closure and an anonymous class instance. The conversion avoids any hidden overhead at runtime. As a practical matter, javac will automatically generate code equivalent to our original client, creating an anonymous class instance in which the body of the lone method corresponds to the body of the closure.
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;We can use the existing &lt;code&gt;Executor&lt;/code&gt; framework to run a closure in the background:
&lt;pre&gt; void sayHello(java.util.concurrent.Executor ex) {
     ex.execute((){ System.out.println("hello"); });
 }
&lt;/pre&gt;
&lt;h2&gt;Further ideas&lt;/h2&gt;
&lt;p&gt;We are considering allowing omission of the argument list in a closure when there are no arguments. Further, we could support a sugar for calls to functions whose last argument is a zero argument closure:
&lt;pre&gt; void foo(T1 p1, ..., Tn pn, R() pn+1) {...}
&lt;/pre&gt;

&lt;p&gt;could be called as
&lt;pre&gt; T1 a1; ... Tn an;
 foo(a1, ..., an){...};
&lt;/pre&gt;
&lt;p&gt;where the call is translated to
&lt;pre&gt; foo(a1, ..., an, {...});
&lt;/pre&gt;
&lt;p&gt;In the special case where there is only one argument to foo, we also would allow
&lt;pre&gt; foo{...}
&lt;/pre&gt;
&lt;p&gt;for example
&lt;pre&gt; void sayHello(java.util.concurrent.Executor ex) {
     ex.execute { System.out.println("hello"); }
 }
&lt;/pre&gt;
&lt;p&gt;We are also experimenting with generalizing this to support an invocation syntax that interleaves parts of the method name and its arguments, which would allow more general user-defined control structures that look like if, if-else, do-while, and so on.

&lt;p&gt;This doesn't play well with the &lt;code&gt;return&lt;/code&gt; statement being given a new meaning within a closure; it returns from the closure instead of the enclosing method/function. Perhaps the return from a closure should be given a different syntax:
&lt;pre&gt; ^ expression;
&lt;/pre&gt;
&lt;p&gt;With this, we probably no longer need the nonlocal return statement.
&lt;h2&gt;Acknowledgments&lt;/h2&gt;
&lt;p&gt;The authors would like to thank the following people whose discussions and insight
have helped us craft, refine, and improve this proposal:
&lt;blockquote&gt;&lt;em&gt;Lars Bak&lt;/em&gt;, &lt;em&gt;Cédric Beust&lt;/em&gt;, &lt;em&gt;Joshua Bloch&lt;/em&gt;, &lt;em&gt;Martin Buchholz&lt;/em&gt;, &lt;em&gt;Danny Coward&lt;/em&gt;, &lt;em&gt;Erik Ernst&lt;/em&gt;, &lt;em&gt;Christian Plesner Hansen&lt;/em&gt;, &lt;em&gt;Doug Lea&lt;/em&gt;, &lt;em&gt;"crazy" Bob Lee&lt;/em&gt;, &lt;em&gt;Martin Odersky&lt;/em&gt;, &lt;em&gt;Tim Peierls&lt;/em&gt;, &lt;em&gt;John Rose&lt;/em&gt;, &lt;em&gt;Ken Russell&lt;/em&gt;, &lt;em&gt;Mads Torgersen&lt;/em&gt;, &lt;em&gt;Jan Vitek&lt;/em&gt;, and &lt;em&gt;Dave Yost&lt;/em&gt;.
&lt;/blockquote&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-115591181028335517?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=115591181028335517' title='35 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115591181028335517'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/115591181028335517'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2006/08/closures-for-java.html' title='Closures for Java'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>35</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-110871097678593429</id><published>2005-02-17T23:15:00.000-08:00</published><updated>2006-10-13T10:42:10.617-07:00</updated><title type='text'>Peripheral Motion Illusions</title><content type='html'>&lt;p&gt;We've been struggling with what to do for the cover art of &lt;a href="http://www.amazon.com/exec/obidos/ASIN/032133678X/wwwgaftercom-20"&gt;&lt;em&gt;Java Puzzlers&lt;/em&gt;&lt;/a&gt;,
and some brainstorming brought us to the idea something like the &lt;a href="http://www.ritsumei.ac.jp/~akitaoka/index-e.html"&gt;amazing optical illusions of professor Akiyoshi Kitaoka&lt;/a&gt;.  They are absolutely mind-blowing.  At first you'll think they are animated GIF images, but I assure you the pictures move when printed on paper too!  Professor Kitaoka has two &lt;a href="http://www.psy.ritsumei.ac.jp/~akitaoka/t2e.html"&gt;books in print&lt;/a&gt;, and plans to publish English translations soon.  In the U.S. you can get the Japanese books from the Kinokuniya bookstore.

&lt;p&gt;I installed Macromedia Freehand FX on my Mac and was able to reproduce some of his &lt;a href="http://www.psy.ritsumei.ac.jp/~akitaoka/rotsnake7.gif"&gt;more stunnning illusions&lt;/a&gt;, and then tried creating some of my own.  &lt;a href="http://www.gafter.com/~neal/Fishwheel5.gif"&gt;Like this one&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-110871097678593429?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=110871097678593429' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/110871097678593429'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/110871097678593429'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2005/02/peripheral-motion-illusions.html' title='Peripheral Motion Illusions'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-110806736709159418</id><published>2005-02-10T13:23:00.000-08:00</published><updated>2006-10-13T10:42:10.548-07:00</updated><title type='text'>"Java Puzzlers" is coming</title><content type='html'>&lt;p&gt;
Amazon is listing my forthcoming book (with Joshua Bloch) for &lt;a href="http://www.amazon.com/exec/obidos/ASIN/032133678X/wwwgaftercom-20"&gt;preordering&lt;/a&gt;: &lt;a href="http://www.javapuzzlers.com"&gt;Java Puzzlers&lt;/a&gt;.  We're having lots of fun getting the material into book form, and the reviewers seems to be very happy with the chapters so far.  Here's what one of them had to say:
&lt;/p&gt;

&lt;blockquote&gt;
I laughed, I cried, I threw up ... my hands in admiration.&lt;br&gt;
-Tim Peierls
&lt;/blockquote&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-110806736709159418?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=110806736709159418' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/110806736709159418'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/110806736709159418'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2005/02/java-puzzlers-is-coming.html' title='&quot;Java Puzzlers&quot; is coming'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7803021.post-109597019009549811</id><published>2004-09-23T13:06:00.000-07:00</published><updated>2006-10-13T10:42:10.472-07:00</updated><title type='text'>Puzzling Through Erasure: answer section</title><content type='html'>&lt;p&gt;&lt;em&gt;Erasure&lt;/em&gt;
is the technique that Java 5 uses to implement generics.&amp;nbsp;
Basically, the javac compiler performs its type-checking and then
erases, or removes, the generic type information from the runtime
representation.&amp;nbsp; &lt;em&gt;Reification&lt;/em&gt;, on the other hand, is the
opposite.&amp;nbsp; A generics implementation based on reification retains
the type parameters at runtime as first-class entities, which allows it
to perform certain type-based language and reflective operations on
type parameters.&amp;nbsp; Sun chose to implement generics using
erasure.&amp;nbsp; C# implements generics using reification.&amp;nbsp; A number
of questions about &lt;em&gt;erasure&lt;/em&gt;
and &lt;em&gt;reification&lt;/em&gt;
have been raised in the context of the new version of the Java
language, and misunderstanding and misinformation abounds.&amp;nbsp; I hope
this
note will help illuminate the issues.&lt;/p&gt;
&lt;p&gt;Why did Sun go with an erasure scheme to implement generics, rather
than reifying type parameters as is done in C#? This is perhaps one
of the least understood aspects of the Java generics design, but it is
a natural conseqence of the design goals of the language extension.
The goal was to provide backwards compatibility of both source and
object code, and also &lt;em&gt;migration&lt;/em&gt; compatibility. The meaning
of backwards compatibility is pretty obvious: you want existing source
and class files to continue to be legal and continue to mean what they
meant before. Although the definition of backwards compatibility is
clear, it is actually very hard to change the language without
violating it.
&lt;/p&gt;
&lt;p&gt;The other design constraint is migration compatibility, and this is
a big one. I'll explain it by way of an example.
&lt;/p&gt;
&lt;h4&gt;Migration Compatibility&lt;/h4&gt;
&lt;p&gt;Migration compatibility is the first constraint among the &lt;a
href="http://www.jcp.org/en/jsr/detail?id=14"&gt;requirements (in section
2.5) for jsr14's design for a generic extension to java&lt;/a&gt;:
&lt;/p&gt;
&lt;blockquote&gt; C1) Upward compatibility with existing
code. Pre-existing code must work on the new system. This implies not
only upward compatibility of the class file format, but also
interoperability of old applications with parameterized versions of
pre-existing libraries, in particular those used in the platform
library and in standard extensions.
&lt;/blockquote&gt;
&lt;p&gt;Consider the following software vendors: Company A sells a Java
library for manipulating Audio. Company B sells a Java library for
controlling electronic Bugles (I think this product would be called &lt;a
href="http://www.minibite.com/oldies/boogiewoogie.htm"&gt;Boogie Woogie
Boy&lt;/a&gt;). Company C sells a software product
that is an electronic Bugle which is built on the libraries from A and
B. C's customers
would normally license all three products.
&lt;/p&gt;
&lt;p&gt;Along comes JDK5, and these companies naturally want to migrate to
generics. Companies A and B are in the comfortable position of
being at the bottom of this software stack, and can immediately begin
developing new versions of their APIs and libraries that take advantage
of the new language features. Being a new release of the product,
Company A would naturally also add new features. Their new API is
called A2. Customers who require library A, for example because they
have not modified their source to take advantage of generics yet,
can still license it.
&lt;/p&gt;
&lt;p&gt;Company B, similarly, ships two libraries B and B2.
&lt;/p&gt;
&lt;p&gt;What does company C do? First, they cannot migrate to the new
version of these libraries until the new libraries are available. And
once they are available, C will want to migrate, for two reasons.
First, it improves their software development process to use the
improved language features. Second, their future customers might
license the new (rather than the old) libraries A2 and B2. So company
C provides two versions of their product, the old version C based on A
and B, and C2 based on A2 and B2.
&lt;/p&gt;
&lt;p&gt;Shortly after releasing C2 (and settling the inevitable trademark
infringement lawsuit with &lt;a href="http://www.coca-cola.com/"&gt;Coca Cola&lt;/a&gt;)
Company C discovers that it has left a
huge number of its customers out in the cold. These are customers who
have licensed the new version of one of the libraries A or B, but not
new versions of both. Neither of C's products will work with these
combinations. So Company C promptly provides C2a and C2b, two new
versions of their product for this subset of customers.
&lt;/p&gt;
&lt;p&gt;Things only get worse as we move up the software stack. First, it
will be a very long time before everyone can migrate fully to the new
APIs. Second, as a library writer you either require your customers
to use the latest version of everything and deprecate your old APIs,
or you support an astronomical number of variations of the underlying
layers. If you're in the enviable position of controlling the entire
software stack then this is no big deal -- except perhaps to your
customers. Sun is not in that position and this situation is clearly
unacceptable.
&lt;/p&gt;
&lt;p&gt;This is where migration compatibility comes in. Migration
compatibility requires that the generic version of an API be
&lt;em&gt;compatible&lt;/em&gt; with the old version, in the sense that existing
clients will continue to compile (for source) and run (for binaries).
This requirement constrains the design space significantly.&lt;/p&gt;
&lt;p&gt;In a system that support migration compatibility, Companies A and B
can independently retrofit their libraries with generics, and their
customers will be able to use the new library without modifying
their source code, even without recompiling it.  But those customers
only gain the benefit of generics in those libraries when they begin
placing type parameters on the generic types.  But Companies A and B
can now ship a single version of their library.
&lt;/p&gt;
&lt;p&gt;We do not know how to satisfy this constraint in a system that also
provides &lt;em&gt;reification&lt;/em&gt;, that is, runtime access to type
parameters. This is not for lack of trying. In fact, we've explored
the design space enough to conjecture that it simply can't be done.
The details of that exploration are very interesting but far beyond
the scope of this note. &lt;a href="http://mindview.net/WebLog/log-0058"&gt;Bruce
Eckel's
&lt;em&gt;injection&lt;/em&gt; idea&lt;/a&gt; is often proposed as a starting point, as
is &lt;a href="http://www.cs.rice.edu/%7Ejavaplt/nextgen/doc/"&gt;NextGen&lt;/a&gt;.
Neither supports migration compatibility.
&lt;/p&gt;
&lt;h4&gt;Backwards compatibility is hard&lt;/h4&gt;
&lt;p&gt;I mentioned earlier that even though the phrase "backwards
compatibility" is easier to understand than migration compatibility,
it is not easy to extend the language without breaking compatibility.
Let's take, for example, Bruce's suggestion
that some future version of Java would begin reifying type parameters
and stop using erasure. His idea is that constructor
invocations for generic classes would pass one or more extra
parameters - type information for the instantiation's type parameters -
which would be stored in the instance.
&lt;/p&gt;
&lt;p&gt;Setting aside the some very difficult implementation and
performance issues (do you really want every linked list node to
double in size? How do you implement &lt;tt&gt;instanceof&lt;/tt&gt; for generic
interfaces? How do you implement array store checks?), this isn't
really backward compatible. The fundamental problem is that existing
Java 5 class files don't follow that convention, and so won't
interoperate with new code. Existing code that instantiates
&lt;tt&gt;Foo&amp;lt;String&amp;gt;&lt;/tt&gt; doesn't in fact pass the extra parameter.
Existing
subclasses of &lt;tt&gt;Foo&lt;/tt&gt; don't pass such data on to the superclass
constructor. Existing implementations of a &lt;tt&gt;Foo&amp;lt;T&amp;gt;&lt;/tt&gt;
interface don't
expect to receive that extra parameter in the constructor.
&lt;/p&gt;
&lt;p&gt;I would also like to address some other misconceptions Bruce Eckel's
two
latest blog entries &lt;a href="http://mindview.net/WebLog/log-0057"&gt;here&lt;/a&gt;
and &lt;a href="http://mindview.net/WebLog/log-0058"&gt;here&lt;/a&gt;.
&lt;/p&gt;
&lt;h4&gt;Why can't I "new T()"?&lt;/h4&gt;
&lt;p&gt;For a type parameter &lt;tt&gt;T&lt;/tt&gt;, the reason you can't do a "&lt;tt&gt;new
T()&lt;/tt&gt;" is
because not every type has a no-arg constructor. I know Bruce is a
big fan of what he calls "latent typing", and he would prefer to get
such errors at runtime. But Java is a statically typed language, for
better or worse, and you simply can't invoke a no-arg constructor on a
type that isn't statically known to have one. It's also true that due
to erasure there would be no way to generate this code, but for this
construct that is beside the point.
&lt;/p&gt;
&lt;h4&gt;What is the point of type parameters if they are erased&lt;/h4&gt;
&lt;p&gt;Static type checking! To belabor the point, if you're someone who
prefers what Bruce calls latent typing, then you care about what you
can do with a type at runtime more than the compile-time utility. If
that's the case, any extension to the static type system is ho-hum
uninteresting and not worth the brain cycles needed to understand it.
&lt;/p&gt;
&lt;p&gt;But for those of us who want to rely on the compiler to help us get
our programs statically correct and prefer our errors be reported
early, generics are a huge win. Generics can save you a great deal of
work and mental energy that used to be necessary mediating untyped
collections with a program that works with concrete types.
&lt;/p&gt;
&lt;h4&gt;How do I create an array of T?&lt;/h4&gt;
&lt;p&gt;There are two answers - a cheat that isn't typesafe but works in
many situations, and a correct answer. Bruce found the cheat, and
it's unfortunate that it is widely being copied as the "correct" way
to do things. At the risk of sending the wrong message, the cheat is
as follows:
&lt;/p&gt;
&lt;pre&gt; T[] a = (T[]) new Object[N]; // Bad style!&lt;br&gt;&lt;/pre&gt;
&lt;p&gt;When you do this sort of thing the compiler will rightfully
complain. After all, an &lt;tt&gt;Object&lt;/tt&gt; array isn't a &lt;tt&gt;T&lt;/tt&gt;
array unless &lt;tt&gt;T&lt;/tt&gt; happens
to be &lt;tt&gt;Object&lt;/tt&gt;. You shouldn't ignore this compiler warning. In
fact,
what you've written here is very dangerous. If you have a method in
the API that returns a &lt;tt&gt;T[]&lt;/tt&gt; and you return this value, and you
have a client for which &lt;tt&gt;T==String&lt;/tt&gt; who tries to store it into
a variable of type &lt;tt&gt;String[]&lt;/tt&gt;, you will get a
&lt;tt&gt;ClassCastException&lt;/tt&gt; at runtime.
&lt;/p&gt;
&lt;p&gt;But wait, you say, this kind of thing appears in the Collections
implementation! So it must be the approved, accepted, proper
approach. No. Mea culpa. I was lazy. It would have been better for
me to use an &lt;tt&gt;Object&lt;/tt&gt; array inside the collection, and add a
cast (yes,
to &lt;tt&gt;T&lt;/tt&gt;) everywhere necessary when an element is removed from
the array. In general, this cast is elided by javac and moved into
the non-generic client, both by virtue of compiling by erasure. But
you still get a complaint from the compiler on each cast. This
warning is unavoidable, because at runtime existing clients simply do
not provide enough type information to do the cast correctly. That's
not due to erasure, it's due to language evolution.
&lt;/p&gt;
&lt;p&gt;But that's not the correct solution. The correction solution
requires that you design your API to be aware of generics
(unfortunately not possible when retrofitting an exising class) and
relies on using the idea of a &lt;em&gt;type token&lt;/em&gt;, which I introduced
along with the generification of the core APIs. See &lt;a
href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf"&gt;section
8 of Gilad Bracha's Generics Tutorial&lt;/a&gt; for more details, as well as
the &lt;a
href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#checkedCollection%28java.util.Collection,%20java.lang.Class%29"&gt;checked
collection wrappers in JDK5&lt;/a&gt; for a straightforward example.
If you're designing an API in which you really, really wish that type
parameters were not erased, you can achieve almost the same effect as
follows:
&lt;/p&gt;
&lt;pre&gt;  class Generic&amp;lt;T&amp;gt; {
    final private Class&amp;lt;T&amp;gt; tClass;
    public Generic(Class&amp;lt;T&amp;gt; tClass) {
      this.tClass = tClass;
    }
  }&lt;/pre&gt;
&lt;p&gt;Now you can instantiate using reflection
(&lt;tt&gt;tClass.newInstance()&lt;/tt&gt;), create arrays (&lt;tt&gt;Array.newInstance&lt;/tt&gt;),
cast (&lt;tt&gt;Class.cast&lt;/tt&gt;), and do instanceof tests (&lt;tt&gt;Class.isInstance&lt;/tt&gt;),
though
with a slightly different syntax than you might prefer.
&lt;/p&gt;
&lt;p&gt;This technique allows you to get the effect of what Bruce calls
"type injection", almost undoing the erasure yourself. Why do I say
"almost"? I'll leave that as a puzzle for you to think about. One
hint: just as you feared, it has something to do with erasure.
&lt;/p&gt;
&lt;h4&gt;Why can't I put bounds on an instantiation?&lt;/h4&gt;
&lt;p&gt;What would it mean? If you were able to make a new &lt;tt&gt;List&amp;lt;?
extends Foo&amp;gt;()&lt;/tt&gt;, then you could place into that list a
&lt;tt&gt;Foo&lt;/tt&gt; or any subclass of &lt;tt&gt;Foo&lt;/tt&gt;. But a sublcass of
&lt;tt&gt;Foo&lt;/tt&gt; is also a &lt;tt&gt;Foo&lt;/tt&gt;, so you could also use a
&lt;tt&gt;List&amp;lt;Foo&amp;gt;&lt;/tt&gt; for the same purpose. In short,
&lt;tt&gt;new List&amp;lt;? extends Foo&amp;gt;()&lt;/tt&gt; would mean the same thing as
&lt;tt&gt;new List&amp;lt;Foo&amp;gt;()&lt;/tt&gt;.
&lt;/p&gt;
&lt;p&gt;To look at it another way, consider method parameters. You can put
a type on a method's value parameter, where the parameter's name is
defined, but not on an argument to a method call, which is an
expression.
The same is true of type parameters and arguments: you can put
a bound on the type parameter, where its name is defined, but not on
the type argument.
&lt;/p&gt;
&lt;h4&gt;Why do you say that C# breaks compatibility with their
generics
system?&lt;/h4&gt;
&lt;p&gt;The short answer is: I don't.&lt;/p&gt;
&lt;p&gt;Microsoft is essentially deprecating the old collections classes by
introducing a new, preferred set of generic collections classes. They
are creating the kinds of problems described in the Company A-B-C
scenario, only it might just be less of a problem for them because
they control so much more of the software stack. I do not claim that
they break backward compatibility. In fact, generally speaking I
prefer reification when it doesn't conflict with the design goals.
The other disadvantage (besides
abandoning migration compatibility) that I see in the &lt;tt&gt;C#&lt;/tt&gt;
approach is
that it is hard to reconcile with both the bipartite type system and
wildcards, though perhaps that problem could be solved.
&lt;/p&gt;
&lt;p&gt;You might not agree with migration compatibility as a goal for the
generics extension to Java. That would have been very useful feedback
in 1999 when jsr14 was formed, and in fact the issue was discussed at
great length at the time. Whatever your feelings, I hope you agree
that now, a month before the product ships, is a poor time to
reconsider the most fundamental design goals that were set five years
earlier for the product and on which the existing design and
implementation depends deeply.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7803021-109597019009549811?l=gafter.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7803021&amp;postID=109597019009549811' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/109597019009549811'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7803021/posts/default/109597019009549811'/><link rel='alternate' type='text/html' href='http://gafter.blogspot.com/2004/09/puzzling-through-erasure-answer.html' title='Puzzling Through Erasure: answer section'/><author><name>Neal Gafter</name><uri>http://www.blogger.com/profile/08579466817032124881</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='28' height='32' src='http://www.gafter.com/~neal/gafter-google.jpg'/></author><thr:total>8</thr:total></entry></feed>
