SlideShare a Scribd company logo
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

More Related Content

KEY
Perl On The JVM (London.pm Talk 2009-04)
Ben Evans
 
KEY
Modern Java Concurrency
Ben Evans
 
PDF
Working With Concurrency In Java 8
Heartin Jacob
 
PPTX
Java and the JVM
Manish Pandit
 
PDF
[Java concurrency]01.thread management
xuehan zhu
 
PDF
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
KEY
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
 
KEY
Rails traps
Reuven Lerner
 
Perl On The JVM (London.pm Talk 2009-04)
Ben Evans
 
Modern Java Concurrency
Ben Evans
 
Working With Concurrency In Java 8
Heartin Jacob
 
Java and the JVM
Manish Pandit
 
[Java concurrency]01.thread management
xuehan zhu
 
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
 
Rails traps
Reuven Lerner
 

What's hot (20)

KEY
Actors and Threads
mperham
 
KEY
Polyglot and Functional Programming (OSCON 2012)
Martijn Verburg
 
KEY
Polyglot and functional (Devoxx Nov/2011)
Martijn Verburg
 
PPT
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
JAX London
 
PDF
A Brief, but Dense, Intro to Scala
Derek Chen-Becker
 
PPTX
Scala in practice
Tomer Gabel
 
PPT
Web development basics (Part-7)
Rajat Pratap Singh
 
KEY
Modern Java Concurrency (Devoxx Nov/2011)
Martijn Verburg
 
PDF
Java 8 selected updates
Vinay H G
 
PPT
Web development basics (Part-5)
Rajat Pratap Singh
 
ODP
Refactoring to Scala DSLs and LiftOff 2009 Recap
Dave Orme
 
PDF
Concurrency in Java
Lakshmi Narasimhan
 
PPTX
Test driven development v1.0
Ganesh Kondal
 
PDF
Actor Patterns and NATS - Boulder Meetup
Apcera
 
PPTX
The Actor Model - Towards Better Concurrency
Dror Bereznitsky
 
PDF
Smalltalk and ruby - 2012-12-08
Koan-Sin Tan
 
PDF
Model Manipulation Using Embedded DSLs in Scala
Filip Krikava
 
PDF
Scalatra 2.2
Ivan Porto Carrero
 
PDF
Polyglot Plugin Programming
Atlassian
 
PDF
A peek into Python's Metaclass and Bytecode from a Smalltalk User
Koan-Sin Tan
 
Actors and Threads
mperham
 
Polyglot and Functional Programming (OSCON 2012)
Martijn Verburg
 
Polyglot and functional (Devoxx Nov/2011)
Martijn Verburg
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
JAX London
 
A Brief, but Dense, Intro to Scala
Derek Chen-Becker
 
Scala in practice
Tomer Gabel
 
Web development basics (Part-7)
Rajat Pratap Singh
 
Modern Java Concurrency (Devoxx Nov/2011)
Martijn Verburg
 
Java 8 selected updates
Vinay H G
 
Web development basics (Part-5)
Rajat Pratap Singh
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Dave Orme
 
Concurrency in Java
Lakshmi Narasimhan
 
Test driven development v1.0
Ganesh Kondal
 
Actor Patterns and NATS - Boulder Meetup
Apcera
 
The Actor Model - Towards Better Concurrency
Dror Bereznitsky
 
Smalltalk and ruby - 2012-12-08
Koan-Sin Tan
 
Model Manipulation Using Embedded DSLs in Scala
Filip Krikava
 
Scalatra 2.2
Ivan Porto Carrero
 
Polyglot Plugin Programming
Atlassian
 
A peek into Python's Metaclass and Bytecode from a Smalltalk User
Koan-Sin Tan
 
Ad

Similar to Java Closures (20)

PDF
Java 8-revealed
Hamed Hatami
 
PDF
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
Chuk-Munn Lee
 
PPTX
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Emiel Paasschens
 
PDF
JSR 335 / java 8 - update reference
sandeepji_choudhary
 
DOCX
Colloquium Report
Mohammad Faizan
 
PPTX
Software Uni Conf October 2014
Nayden Gochev
 
PPTX
Java 8 - An Overview
Indrajit Das
 
PPTX
What`s New in Java 8
Mohsen Zainalpour
 
PDF
Java SE 8 & EE 7 Launch
Digicomp Academy AG
 
PPTX
Lambda functions in java 8
James Brown
 
PPTX
55 New Features in Java SE 8
Simon Ritter
 
PDF
Java 8 Overview
Nicola Pedot
 
PDF
Java SE 8
Simon Ritter
 
PDF
Eclipse and Java 8 - Eclipse Day India 2013
Noopur Gupta
 
PPTX
A brief tour of modern Java
Sina Madani
 
PPTX
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Olena Syrota
 
PDF
JDT embraces lambda expressions
Eclipse Day India
 
PPTX
Beginning Java for .NET developers
Andrei Rinea
 
PDF
Using Java 8 on Android
Eduardo Felipe Ewert Bonet
 
PPTX
Java8: what's new and what's hot
Sergii Maliarov
 
Java 8-revealed
Hamed Hatami
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
Chuk-Munn Lee
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Emiel Paasschens
 
JSR 335 / java 8 - update reference
sandeepji_choudhary
 
Colloquium Report
Mohammad Faizan
 
Software Uni Conf October 2014
Nayden Gochev
 
Java 8 - An Overview
Indrajit Das
 
What`s New in Java 8
Mohsen Zainalpour
 
Java SE 8 & EE 7 Launch
Digicomp Academy AG
 
Lambda functions in java 8
James Brown
 
55 New Features in Java SE 8
Simon Ritter
 
Java 8 Overview
Nicola Pedot
 
Java SE 8
Simon Ritter
 
Eclipse and Java 8 - Eclipse Day India 2013
Noopur Gupta
 
A brief tour of modern Java
Sina Madani
 
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Olena Syrota
 
JDT embraces lambda expressions
Eclipse Day India
 
Beginning Java for .NET developers
Andrei Rinea
 
Using Java 8 on Android
Eduardo Felipe Ewert Bonet
 
Java8: what's new and what's hot
Sergii Maliarov
 
Ad

Recently uploaded (20)

PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PPTX
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 

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

Editor's Notes