SlideShare una empresa de Scribd logo
1 de 17
Implementing Closures
in Java (and on the JVM)
Ben Evans, TeamSparq, LJC, Java
SE Exec Committee, etc
What do we mean by Closures Anyway?

• An age-old argument.
• Here’s what I mean by it (YMMV):

• A unit of deferred execution
• A bit of code that can be passed around like a
  value
• Can be used as the RHS of an assignment
  statement
• Capture the relevant part of the lexical
  environment they were created in
Inner Classes

• One trick we see a lot of in Java is the “tiny anonymous inner class”
• Used in CallbackHandlers, Runnables and all sorts of other
  situations.
• These are a way to implement Lambdas / Closures
    – Objects are values
    – Classes can capture local state
    – They can do deferred execution
• Let’s take a look at an example (and not a standard
  CallbackHandler or Runnable)
A Simple Example




• Very simple example...
• So I won’t need to spend very much time on it at all...
Aside: Did You Spot The Important Word?

•   The important word is “final”
•   This means that captured variables are immutable
•   Some people don’t like this
•   But there are interactions with multithreaded code to worry about
•   You can always defeat it with the array-of-1 trick
•   But that doesn’t mean that you should
•   Mutable state is often the enemy. We shouldn’t be encouraging it
Oh, OK Then...




• Now it should be quite a bit clearer what’s going on.
• How are we going to represent our new Closures / function-
  like units of code? Is this a good way?
Function Types

• Function<X, Y> looks like a good bet
  for a function type
• This is an example of a structural type
• However, what about Type Erasure?
• Java is a strongly-typed language
    – Closures & lambdas have to be
      strongly-typed
• What about Reified Generics?
• Can we represent our Function-like
  objects in a different way?
• Groundwork for some of this was laid
  in Java 7 – most of this is due in 8
  though
SAM Types and Auto-Conversion

• Function types have some problems
• We don’t want to introduce structural typing
• What else can we do?
• Enter the SAM type – Single Abstract Method
• One way of thinking about a lambda / closure is as an
  implementation of a interface with just 1 method (method signature
  matters, though)
• If the type signature is compatible, shouldn’t we be able to auto-
  convert between two different SAM types?
• We also need method literals, e.g. Object#toString
• What should the syntax look like?
Grammar & Syntax

For the BNF Grammar-hounds:

lambda = ArgList Arrow Body
  ArgList = Identifier
        | NilaryArgList
        | "(" Identifier [ "," Identifier ]* ")"
        | "(" Type Identifier [ "," Type Identifier ]* ")"
  Body = Expression
        | "{" [ Statement ";" ]+ "}“

This is pretty much identical to the C# and Scala syntax
There are good and bad things about this – no syntax is perfect, and this one has
its share of downsides.

However, this is the syntax, so get used to it & move on
Syntax Example - java.util.concurrent




• Eclipse doesn’t like the syntax yet
• We have a lambda standing in as a Runnable (and closing over
  hndl)
• So far, just retrofitting to existing APIs
Syntax




•   Eclipse still doesn’t like the syntax
•   In fact, Eclipse doesn’t really like the Java 7 <> syntax yet
•   Note the type inference of x
•   Classic example of “slightly functional programming”
•   The map() takes a function which maps Integer -> Integer
•   The filter() takes a function which maps Integer -> boolean
•   However, there’s something wrong with the above...
Backwards Compatibility & Interfaces

• Java is always very keen not to break backwards compatibility
• There are no map(), filter() etc methods on the Java collections
  today
• Adding them to the core collections interfaces would break
  backwards compatibility.
• Pre-8 class files would no longer be able to link against new code
• This would be very bad
• But we want our Lambdas / Closures!
• Need to do something different / smarter
Default and Extension Methods

• Idea: Weave a default implementation into classes which are
  missing their own at class load time
• Add a synthetic method which is wired in using invokedynamic and
  Method Handles
• Called “public defender” or Miranda methods
• New Java language keywords:
   – “extension” indicates that a method in an interface does not need to be
     implemented
   – “default” indicates which method should be used as the fall-back
       • Use the AbstractFoo implementation class of Foo (if it exists)
       • Or specify another method (probably as a method reference)
Work In Progress - Come and Help Out

•   All this work is happening now
•   OpenJDK 8 is rolling along
•   Java 8 is now targeted at Summer 2013
•   jdk8-dev is the mailing list
•   As of yesterday, the pre-built developer preview is out:
•   http://jdk8.java.net/download.html
•   Get involved and have a play
•   Block, Mapper, Predicate and their friends in java.util.functions are
    waiting for you...
         •
Thank You – Questions?




http://www.teamsparq.net

                 Twitter: @kittylyst



                             http://www.java7developer.com
Bonus – Retrofitting the implementation

• In Java 8, Closures are SAM types
• They can’t be anything else – there isn’t anything for them to be.
• Everything is either a ref type (ie an object) or a primitive type.
• But we can imagine a future version of Java (maybe 9) which had
  new VM structures
• “Typesafe function pointer primitives”
• The spec for lambdas is being written to allow for possible future,
  non-class-based implementations
• This would also be important to bring this tech to Java ME-like
  platforms
Bonus - Beyond Closures

•   Coroutines
•   Producer / consumer shares
•   Collaborating threadpool
•   Continuations
•   Tuples
•   Could some of these make Java 8 (or 9) ?
•   Active group involved in working in this space - contact me for more
    details

Más contenido relacionado

La actualidad más candente

Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
JAX London
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
Vinay H G
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin Programming
Atlassian
 

La actualidad más candente (20)

Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
 
Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)
 
Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Web development basics (Part-7)
Web development basics (Part-7)Web development basics (Part-7)
Web development basics (Part-7)
 
Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
Web development basics (Part-5)
Web development basics (Part-5)Web development basics (Part-5)
Web development basics (Part-5)
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
Concurrency in Java
Concurrency in JavaConcurrency in Java
Concurrency in Java
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
 
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder Meetup
 
The Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyThe Actor Model - Towards Better Concurrency
The Actor Model - Towards Better Concurrency
 
Smalltalk and ruby - 2012-12-08
Smalltalk and ruby  - 2012-12-08Smalltalk and ruby  - 2012-12-08
Smalltalk and ruby - 2012-12-08
 
Model Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in ScalaModel Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in Scala
 
Scalatra 2.2
Scalatra 2.2Scalatra 2.2
Scalatra 2.2
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin Programming
 
A peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk UserA peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk User
 

Similar a Java Closures

Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
rsebbe
 

Similar a Java Closures (20)

JSR 335 / java 8 - update reference
JSR 335 / java 8 - update referenceJSR 335 / java 8 - update reference
JSR 335 / java 8 - update reference
 
Lambda Expressions Java 8 Features usage
Lambda Expressions  Java 8 Features usageLambda Expressions  Java 8 Features usage
Lambda Expressions Java 8 Features usage
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developers
 
Comparing Golang and understanding Java Value Types
Comparing Golang and understanding Java Value TypesComparing Golang and understanding Java Value Types
Comparing Golang and understanding Java Value Types
 
Software Engineering Thailand: Programming with Scala
Software Engineering Thailand: Programming with ScalaSoftware Engineering Thailand: Programming with Scala
Software Engineering Thailand: Programming with Scala
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Rootcon X - Reverse Engineering Swift Applications
Rootcon X - Reverse Engineering Swift ApplicationsRootcon X - Reverse Engineering Swift Applications
Rootcon X - Reverse Engineering Swift Applications
 
Introduction to Clojure
Introduction to ClojureIntroduction to Clojure
Introduction to Clojure
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John Mulhall
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigou
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Introducing Scala to your Ruby/Java Shop : My experiences at IGNIntroducing Scala to your Ruby/Java Shop : My experiences at IGN
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
 
Scala adoption by enterprises
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprises
 
Java programming language
Java programming languageJava programming language
Java programming language
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Java Closures

  • 1. Implementing Closures in Java (and on the JVM) Ben Evans, TeamSparq, LJC, Java SE Exec Committee, etc
  • 2. What do we mean by Closures Anyway? • An age-old argument. • Here’s what I mean by it (YMMV): • A unit of deferred execution • A bit of code that can be passed around like a value • Can be used as the RHS of an assignment statement • Capture the relevant part of the lexical environment they were created in
  • 3. Inner Classes • One trick we see a lot of in Java is the “tiny anonymous inner class” • Used in CallbackHandlers, Runnables and all sorts of other situations. • These are a way to implement Lambdas / Closures – Objects are values – Classes can capture local state – They can do deferred execution • Let’s take a look at an example (and not a standard CallbackHandler or Runnable)
  • 4. A Simple Example • Very simple example... • So I won’t need to spend very much time on it at all...
  • 5. Aside: Did You Spot The Important Word? • The important word is “final” • This means that captured variables are immutable • Some people don’t like this • But there are interactions with multithreaded code to worry about • You can always defeat it with the array-of-1 trick • But that doesn’t mean that you should • Mutable state is often the enemy. We shouldn’t be encouraging it
  • 6. Oh, OK Then... • Now it should be quite a bit clearer what’s going on. • How are we going to represent our new Closures / function- like units of code? Is this a good way?
  • 7. Function Types • Function<X, Y> looks like a good bet for a function type • This is an example of a structural type • However, what about Type Erasure? • Java is a strongly-typed language – Closures & lambdas have to be strongly-typed • What about Reified Generics? • Can we represent our Function-like objects in a different way? • Groundwork for some of this was laid in Java 7 – most of this is due in 8 though
  • 8. SAM Types and Auto-Conversion • Function types have some problems • We don’t want to introduce structural typing • What else can we do? • Enter the SAM type – Single Abstract Method • One way of thinking about a lambda / closure is as an implementation of a interface with just 1 method (method signature matters, though) • If the type signature is compatible, shouldn’t we be able to auto- convert between two different SAM types? • We also need method literals, e.g. Object#toString • What should the syntax look like?
  • 9. Grammar & Syntax For the BNF Grammar-hounds: lambda = ArgList Arrow Body ArgList = Identifier | NilaryArgList | "(" Identifier [ "," Identifier ]* ")" | "(" Type Identifier [ "," Type Identifier ]* ")" Body = Expression | "{" [ Statement ";" ]+ "}“ This is pretty much identical to the C# and Scala syntax There are good and bad things about this – no syntax is perfect, and this one has its share of downsides. However, this is the syntax, so get used to it & move on
  • 10. Syntax Example - java.util.concurrent • Eclipse doesn’t like the syntax yet • We have a lambda standing in as a Runnable (and closing over hndl) • So far, just retrofitting to existing APIs
  • 11. Syntax • Eclipse still doesn’t like the syntax • In fact, Eclipse doesn’t really like the Java 7 <> syntax yet • Note the type inference of x • Classic example of “slightly functional programming” • The map() takes a function which maps Integer -> Integer • The filter() takes a function which maps Integer -> boolean • However, there’s something wrong with the above...
  • 12. Backwards Compatibility & Interfaces • Java is always very keen not to break backwards compatibility • There are no map(), filter() etc methods on the Java collections today • Adding them to the core collections interfaces would break backwards compatibility. • Pre-8 class files would no longer be able to link against new code • This would be very bad • But we want our Lambdas / Closures! • Need to do something different / smarter
  • 13. Default and Extension Methods • Idea: Weave a default implementation into classes which are missing their own at class load time • Add a synthetic method which is wired in using invokedynamic and Method Handles • Called “public defender” or Miranda methods • New Java language keywords: – “extension” indicates that a method in an interface does not need to be implemented – “default” indicates which method should be used as the fall-back • Use the AbstractFoo implementation class of Foo (if it exists) • Or specify another method (probably as a method reference)
  • 14. Work In Progress - Come and Help Out • All this work is happening now • OpenJDK 8 is rolling along • Java 8 is now targeted at Summer 2013 • jdk8-dev is the mailing list • As of yesterday, the pre-built developer preview is out: • http://jdk8.java.net/download.html • Get involved and have a play • Block, Mapper, Predicate and their friends in java.util.functions are waiting for you... •
  • 15. Thank You – Questions? http://www.teamsparq.net Twitter: @kittylyst http://www.java7developer.com
  • 16. Bonus – Retrofitting the implementation • In Java 8, Closures are SAM types • They can’t be anything else – there isn’t anything for them to be. • Everything is either a ref type (ie an object) or a primitive type. • But we can imagine a future version of Java (maybe 9) which had new VM structures • “Typesafe function pointer primitives” • The spec for lambdas is being written to allow for possible future, non-class-based implementations • This would also be important to bring this tech to Java ME-like platforms
  • 17. Bonus - Beyond Closures • Coroutines • Producer / consumer shares • Collaborating threadpool • Continuations • Tuples • Could some of these make Java 8 (or 9) ? • Active group involved in working in this space - contact me for more details

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n