SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threadsmperham
 
Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Martijn Verburg
 
Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Martijn Verburg
 
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 EvansJAX London
 
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 ScalaDerek Chen-Becker
 
Scala in practice
Scala in practiceScala in practice
Scala in practiceTomer Gabel
 
Web development basics (Part-7)
Web development basics (Part-7)Web development basics (Part-7)
Web development basics (Part-7)Rajat Pratap Singh
 
Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Martijn Verburg
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 
Web development basics (Part-5)
Web development basics (Part-5)Web development basics (Part-5)
Web development basics (Part-5)Rajat Pratap Singh
 
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 RecapDave Orme
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0Ganesh Kondal
 
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupApcera
 
The Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyThe Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyDror Bereznitsky
 
Smalltalk and ruby - 2012-12-08
Smalltalk and ruby  - 2012-12-08Smalltalk and ruby  - 2012-12-08
Smalltalk and ruby - 2012-12-08Koan-Sin Tan
 
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 ScalaFilip Krikava
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin ProgrammingAtlassian
 
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 UserKoan-Sin Tan
 

Was ist angesagt? (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
 

Ähnlich wie Java Closures

JSR 335 / java 8 - update reference
JSR 335 / java 8 - update referenceJSR 335 / java 8 - update reference
JSR 335 / java 8 - update referencesandeepji_choudhary
 
Lambda Expressions Java 8 Features usage
Lambda Expressions  Java 8 Features usageLambda Expressions  Java 8 Features usage
Lambda Expressions Java 8 Features usageAsmaShaikh478737
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinayViplav Jain
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8 Bansilal Haudakari
 
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 itlokeshpappaka10
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developersAndrei Rinea
 
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 TypesPéter Verhás
 
Software Engineering Thailand: Programming with Scala
Software Engineering Thailand: Programming with ScalaSoftware Engineering Thailand: Programming with Scala
Software Engineering Thailand: Programming with ScalaBrian Topping
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Rootcon X - Reverse Engineering Swift Applications
Rootcon X - Reverse Engineering Swift ApplicationsRootcon X - Reverse Engineering Swift Applications
Rootcon X - Reverse Engineering Swift Applicationseightbit
 
Introduction to Clojure
Introduction to ClojureIntroduction to Clojure
Introduction to ClojureRenzo Borgatti
 
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 MulhallJohn Mulhall
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigoujaxconf
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Codersebbe
 
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 IGNManish Pandit
 
Scala adoption by enterprises
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprisesMike Slinn
 
Java programming language
Java programming languageJava programming language
Java programming languageSubhashKumar329
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Kürzlich hochgeladen (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

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

Hinweis der Redaktion

  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