Joine Music

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Monday, 28 May 2007

JavaOne 2007 - Closures for the Java Language - TS-2294 and BOF-2358 Notes

Posted on 07:36 by Unknown
NOTE: This is an aggregation of the notes I took from Neal Gafter's two sessions at JavaOne 2007 on his Closures for the Java Language proposal.

"Why add closures? Isn't Java complicated enough already?"
“ In another thirty years people will laugh at anyone who tries to invent a language without closures, just as they'll laugh now at anyone who tries to invent a language without recursion.” — Mark Jason Dominus

Goals of the Closures Spec Proposal
  • Provide concise "function" literals - without the pain of anonymous instances (i.e. anonymous inner classes)
  • Interoperate with existing APIs (esp. java.util Collections)
  • Solve problems which Anonymous Inner Classes can't - simplify
  • Enable control APIs (c.f. Scala, Ruby)
  • Wrapped code not changed
  • Function and aggregate operations
  • Write methods which act like new keywords (but only act like)
  • Simple but powerful
Definitions
  • A "closure" is a function which refers to free variables in its lexical context where a "function" is a block of code with parameters that may produce a result value.
  • A "free variable" is an identifier used but not defined by the closure.
  • "Control APIs" are API specific statement forms on a par with built in statements, like special methods.
Problems with anonymous instances
  • Verbose, extra wordy, clumsy, redundant - whereas closures are concise
  • They incompletely capture the lexical context - i.e. "this" and "toString( )" don't refer to what they ought; return, break and continue operate differently also, and you cannot use non final local variables
  • Consequently they force irrelevant refactoring
  • Control APIs are not possible - You cannot wrap arbitrary blocks of code
Specification
Syntax - Closure Expressions
{int x => x+1}
{int x, int y => x+y}
{String x => Integer.parseInt(x)}
{=> System.out.println(“hello”);}
Primary:
Closure
Closure:
{ FormalParameterDecls opt => BlockStatements opt Expression opt }
  • Creates an object which represents code of the body and the lexical context
  • Few restrictions - may access local variables and this and may return from the enclosing method
The closure conversion turns a closure into an instance of some interface
  • This provides interoperability with existing APIS
  • Means you can restrict the closures operations (but you must do this explicitly. It is not done for you by default)
  • If there is not target type, it will use the natural function type
Syntax - Function Types
{int => int}
{int, int => int}
{String => int throws NumberFormatException}
{ => void}
{T => U}
Type:
{TypeList opt => Type FunctionThrows opt }

{String => int throws NumberFormatException} is shorthand for java.lang.function.IO where
package java.lang.function;
public interface IO {
int invoke(A a0) throws X;
}
  • Function types are "ordinary" interface types with an invoke method
  • You can extend and implement them
  • They can declare variables, parameters, return types etc.
  • (There are no special type rules)
Syntax - Control Statements
withLock(lock, {=>
doSomething();
});
withLock(lock) {
doSomething();
}
ControlStatement:
for opt Primary ( Formals : ExpressionList opt ) Statement
for opt Primary ( ExpressionList opt ) Statement

Is translated to:
Primary( ExpressionList, { Formals => Statement });

Examples
1. Control APIs - Perform some operation while holding a java.util.concurrent.Lock
(a) Today:
void incrementBalance(int deposit) {
myLock.lock();
try {
balance += deposit;
} finally {
myLock.unlock();
}
}
(b) Using a proposed new closure-based API:
void incrementBalance(int deposit) {
Locks.withLock(myLock,
{ => balance += deposit; });
}
(c) Using the control statement syntax:
void incrementBalance(int deposit) {
Locks.withLock(myLock) {
balance += deposit;
}
}
2. Aggregate Operations - Make a new list by applying a function to each element of an existing list:
List parseInts(List strings)
throws NumberFormatException {
return Collections.map(
strings, {String s => Integer.decode(s)});
}
3. Interaction with existing APIs - launch a task using an executor
(a) Today:
void launch(Executor ex) {
ex.execute(new Runnable() {
public void run() {
doSomething();
}
});
}
(b) Useing a closure:
void launch(Executor ex) {
ex.execute({ =>
doSomething();
});
}
(c) Using the control statement syntax:
void launch(Executor ex) {
ex.execute() {
doSomething();
}
}
3. Interaction with existing APIs - Add a Swing listener
(a) Today:
void addListener(final ItemSelectable is) {
is.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e)
{ doSomething(e, is); }
}
);
}
(b) Using a closure:
void addListener(final ItemSelectable is) {
is.addItemListener(
{ ItemEvent e => doSomething(e, is); }
);
}
(c) Using the control statement syntax:
void addListener(final ItemSelectable is) {
is.addItemListener(ItemEvent e :) {
doSomething(e, is);
}
}
New APIs
  • API specific control constructs - Collections (e.g. Map Specific iteration), concurrency (e.g. locking) and closables (e.g. resource streams closed automatically at the end of a block)
  • Aggregate operations. E.g.:
List list = …;
Integer sum = Collections.reduce(
list,
{Integer x, Integer y => x+y});
  • Functional primitives

Questions from the Audience
"How do you deal with the namespace issue?"
  • A closure is a method name therefore you have your own scope
  • Use an import statement - a closure is just an API method
"Have you thought of restricting the use of closures? i.e. a member variable which is a closure which extends a generic"
  • No, no one can determine what is and what isn't useful. Just because you can't think of a use case, doesn't mean someone else won't. The only reason you would do something is because you need to.
  • The proposal includes ways for all API writers to restrict how closures are used with them, but blanket restrictions would be trouble.
"How do closures get executed?"
  • The closure expression has parameter types, a return type, and types it uses within it. The compiler analyses this but does not go and impose this on the closure.
  • It works like overloader resolution - it picks which is most specific, therefore there is no type inference but there is a compatability rule.
"How do I pass multiple parameters?"
  • You don't need to. Everything outside the closure can be accessed from within the closure.
"How do we evaluate whether we should add 'this'? - and will it make Java simpler?"
  • It will make it easier to write and read. ("I'm hoping for a video with a Star Wars theme to help me decide") Java today is not the easy Java we had in 1999
Where Can I Read / Hear More?
  • TS Slides
  • TS Audio (to come)
  • BOF Audio (to come)
  • Java.net community corner podcast
  • Neal's Blog
  • Stephen Colebourne's blog
Email ThisBlogThis!Share to XShare to Facebook
Posted in gafter closures java javaone notes | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • (no title)
    The Significance and Importance of Quotes in JSTL EL I just spent a few hours debuggung a null pointer in a Portlet JSP I'm writing. It...
  • (no title)
    Agile Development Ramblings: Part I Introduction I've just completed my first Agile development project. We developed a fully functiona...
  • EJB 3.0 Outside the Container, Inside the JVM - Part 2: Configuring JPA Declaratively
    Welcome to part two of this blog entry introducing using EJB3.0 inside the JVM. Click here to view the first part. As we've seen, JPA ...
  • Reuse (ii): Definition of Done
    As I said in my previous post , our project has suddenly taken a new path. There are two bits of collateral which I'd recently produced...
  • Notes from the FindBugs BOF9231 at JavaOne 2007
    NOTE: These are my incomplete notes from the FindBugs BOF at JavaOne 2007. I got in late due to the crush outside so missed the start of th...
  • Writing Unit Tests to Ensure Your "@Transactional ... rollbackFor" Annotations are Honoured
    Thanks to Russ Hart for providing the info on how to get this to work.  I just cut and paste, and then blogged it. It's nice to write un...
  • (no title)
    Can Your Own Demo I found something great on t'internet the other day. I had been asked to do a demo of our new ystem to some users but...
  • JavaOne Bred Over-Enthusiasm...
    I want to build and fiddle with Wonderland , and my own JDK ! The problem is my graphics card sucks (I need acceleration) and I'm runnin...
  • Booting Apache Derby ("JavaDB") with your Java App's Startup
    If you're embedding the Derby RDBMS with your java desktop application and want it to start when you start your app, you need to make th...
  • STS and RTC – Getting them to Play Nice
    We’re developing our new app using Spring 3.0 RC1 and we want the best tools available. We’ve picked the following: SpringSource Tools ...

Categories

  • 0
  • 2008
  • ant maven pimp build javaone 2008
  • apple ipod touch
  • asm
  • blog new ruby
  • blogtag list
  • bond casinoroyale mashup mi6 film movie
  • build
  • bytecode
  • CI
  • cobertura
  • communityone 2008 nutter jvm scala jruby groovy davinci
  • communityone 2008 opensocial socialsite
  • communityone javaone keynote oreilly
  • configuration
  • cowley
  • css div layout column ie firefox safari example
  • custom
  • darkstar mpk20 wonderland java3d commaboration SL
  • dashboard rss communication news development
  • db2 database SQL max min howto tip
  • db2 database ibm lessons tips
  • db2 database load batch howto example
  • db2 import upload data howto command
  • debt technical java annotation
  • debugging tips javaone 2008
  • development web2.0
  • findbugs JavaOne 2008 pugh
  • findbugs JavaOne BOF notes
  • gafter closures java javaone notes
  • google trouble patriarchal patriarchy
  • groovy metaprogramming javaone 2008
  • grubby oss data generation project announce
  • guice javaone 2008
  • gwt maven howto example simple
  • howto
  • hudson
  • hudson CI javaone 2008
  • ibm
  • invokeDynamic jvm dynamic ruby javaone
  • itinerant web2.0 portable desktop
  • jacl was websphere wsadmin trace logging
  • james gosling sun java open source tech days second life SL
  • jar java manifest properties config howto tip
  • java
  • java applet javaone 2008 reloaded jnlp
  • java javafxscript javaone 2008 fxscript
  • java javaone 2007 07
  • java javaone 2008 bytecode cobertura asm singleton testability
  • javaone
  • javaone keynote gage schwarz javafx
  • javaone semantic web bof notes web3
  • jazz
  • jruby rails javaone charlesnutter thomasenebo
  • jruby ruby netbeans development
  • kill dead laptop computer rebuild restore
  • lessonslearned
  • mac osx java gui shellscript classpath problem solution
  • maven plugin unittest test packager
  • mylin mylar javaone eclipse 2008
  • netbeans development ide
  • netbeans development ide RC
  • netbeans maven2 profiling
  • netbeans ruby sun tech days visual web pack roman strobl
  • ola bini java javaone 2008 thoughtworks ruby jruby
  • openjdk java javaone javafx wonderland
  • overheard
  • pojo ejb3.0 jpa orm java example howto
  • rant
  • rest restful jsr311 java web2.0 javaone ts-6411
  • rome rss feed blog rss atom propono java javaone
  • rsa uml profile plugin howto
  • ruby inheritance example
  • ruby jruby rss xml hpricot
  • ruby unless example
  • scm
  • setup
  • subversion svn xp windows cleanup
  • sun java soa web2.0 netbeans opensource javacaps
  • sun tech days java derby database rdbms london
  • sun tech days london impressions
  • terracotta java javaone 2008 android gwt
  • tip
  • tips
  • vwp netbeans JPA howto
  • was jython scripting nfr ibm pmi jvm
  • was tpv jython scripting nfr ibm pmi
  • webrick ruby jruby actadiurna investigation code howto
  • workitem

Blog Archive

  • ►  2012 (1)
    • ►  October (1)
  • ►  2010 (8)
    • ►  November (1)
    • ►  October (3)
    • ►  June (1)
    • ►  May (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2009 (9)
    • ►  December (1)
    • ►  November (5)
    • ►  March (2)
    • ►  February (1)
  • ►  2008 (22)
    • ►  December (1)
    • ►  November (3)
    • ►  May (15)
    • ►  March (1)
    • ►  January (2)
  • ▼  2007 (53)
    • ►  December (1)
    • ►  November (3)
    • ►  September (3)
    • ►  August (2)
    • ►  July (3)
    • ►  June (1)
    • ▼  May (12)
      • Notes from the FindBugs BOF9231 at JavaOne 2007
      • JavaOne 2007 - Closures for the Java Language - TS...
      • RESTful Web Services: JSR-311 (TS-6411) at JavaOne...
      • JRuby on Rails - Agility for the Enterprise (TS-93...
      • JavaOne Bred Over-Enthusiasm...
      • Dynamic Languages in the JVM - Discussion Notes fr...
      • Notes: Beyond Blogging: Feeds In Action Technical ...
      • Project Wonderland BOF (BOF-1306) @ JavaOne 2007
      • JavaOne 2007 Day One Keynote - Ubiquitous JVMs
      • JavaOne 2007 (Day 1 – CommunityOne) Keynote with ...
      • JavaOne 2007 (Day 1 – CommunityOne) Hot, Damn Hot
      • Going to JavaOne 2007...
    • ►  April (5)
    • ►  March (13)
    • ►  February (7)
    • ►  January (3)
  • ►  2006 (35)
    • ►  December (8)
    • ►  October (1)
    • ►  August (1)
    • ►  July (5)
    • ►  June (8)
    • ►  May (3)
    • ►  April (7)
    • ►  March (2)
Powered by Blogger.

About Me

Unknown
View my complete profile