SlideShare una empresa de Scribd logo
1 de 48
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 131
Project Lambda in Java SE 8
Daniel Smith
Java Language Designer
Thursday, November 8, 12
InfoQ.com: News & Community Site
• 750,000 unique visitors/month
• Published in 4 languages (English, Chinese, Japanese and Brazilian
Portuguese)
• Post content from our QCon conferences
• News 15-20 / week
• Articles 3-4 / week
• Presentations (videos) 12-15 / week
• Interviews 2-3 / week
• Books 1 / month
Watch the video with slide
synchronization on InfoQ.com!
http://www.infoq.com/presentations
/Project-Lambda-Java-SE-8-SF
Presented at QCon San Francisco
www.qconsf.com
Purpose of QCon
- to empower software development by facilitating the spread of
knowledge and innovation
Strategy
- practitioner-driven conference designed for YOU: influencers of
change and innovation in your teams
- speakers and topics driving the evolution and innovation
- connecting and catalyzing the influencers and innovators
Highlights
- attended by more than 12,000 delegates since 2007
- held in 9 cities worldwide
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 132
The following is intended to outline our general product direction. It is intended
for information purposes only, and may not be incorporated into any contract.
It is not a commitment to deliver any material, code, or functionality, and should
not be relied upon in making purchasing decisions. The development, release,
and timing of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
The Java Programming Language
•Around 9,000,000 developers worldwide
•17 years old
•4 major revisions (1996, 1997, 2004, 2013...)
•[Insert staggering number] of companies very heavily invested
•Formally standardized and evolved via community
3
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Evolving a Major Language
•Adapting to change
•Righting what’s wrong
•Maintaining compatibility
•Preserving the core
4
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 135
Project Lambda:
Function Values in Java
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Object subclass: Widget [
draw: canvas [ ... ]
click [ ... ]
]
gui add:(Widget new).
(define f
(lambda (x) (* x x)))
(map nums f)
Code as Data
6
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
interface Runnable {
void run();
}
Thread hello = new Thread(new Runnable() {
public void run() {
System.out.println(“Hello, world!”);
}
});
Status Quo in Java 1.1
7
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
interface Predicate<T> {
boolean accept(T arg);
}
lines.removeAll(new Predicate<String>() {
public boolean accept(String line) {
return line.startsWith(“#”);
}
});
Status Quo in Java 5
8
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
interface Predicate<T> {
boolean accept(T arg);
}
lines.removeAll(line -> line.startsWith(“#”));
What We Wish It Looked Like
9
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Why Functions in Java? Adapting to Change
10
•Widely-adopted programming style
• 1995: functions-as-values is too hard to understand
• Now: almost everybody has them (even C++)
•Physical constraints cause changing models
• 1995: sequential execution, mutation
• Today: concurrency, immutability
•A gentle push in the right direction
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Why Functions in Java? Better Libraries
11
•Lots of applications...
•Our priorities:
• Collections
• Concurrency
public class ForkBlur extends RecursiveAction {
private int[] mSource;
private int mStart;
private int mLength;
private int[] mDestination;
public ForkBlur(int[] src, int start, int length, int[] dst) {
mSource = src;
mStart = start;
mLength = length;
mDestination = dst;
}
// Average pixels from source, write results into destination.
protected void computeDirectly() {
for (int index = mStart; index < mStart + mLength; index++) {
mDestination[index] = blur(index, mSource);
}
}
protected static int sThreshold = 10000;
protected void compute() {
if (mLength < sThreshold) {
computeDirectly();
return;
}
int split = mLength / 2;
invokeAll(new ForkBlur(mSource, mStart, split, mDestination),
new ForkBlur(mSource, mStart + split, mLength - split, mDestination));
}
}
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Brief History
•1997: Odersky/Wadler experimental “Pizza” work
•1997: Java 1.1 with anonymous classes
•2006-2008: Vigorous community debate
•2009: OpenJDK Project Lambda formed
•2010: JSR 335 filed
12
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1313
Java 8 Language Concepts & Features
 Lambda expressions
 Functional interfaces
 Target typing
 Method references
 Default methods
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Lambda Expressions
14
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
widget -> {
if (flag) widget.poke();
else widget.prod();
}
(int x, int y) -> {
assert x < y;
return x*y;
}
x -> x+1
(s,i) -> s.substring(0,i)
(Integer i) -> list.add(i)
() -> System.out.print(“x”)
cond -> cond ? 23 : 57
Lambda Expressions
15
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
void cut(List<String> l,
int len) {
l.updateAll(s ->
s.substring(0, len));
}
Variable Capture
16
•Lambdas can refer to variables
declared outside the body
•These variables can be final or
“effectively final”
• Works for anonymous classes,
too
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Meaning of Names in Lambdas
17
•Anonymous classes introduce a new “level” of scope
• ‘this’ means the inner class instance
• ‘ClassName.this’ is used to get to the enclosing class instance
• Inherited names can shadow outer-scope names
•Lambdas reside in the same “level” as the enclosing context
• this refers to the enclosing class
• No new names are inherited
• Like local variables, parameter names can’t shadow other locals
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Functional Interfaces
18
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
String -> int
(String, int, boolean) -> List<? extends Integer>
(String, Number) -> Class<?> throws IOException
Function Types in Java?
19
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Function Types in Java: Functional Interfaces
20
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Common Existing Functional Interfaces
•java.lang.Runnable
•java.util.concurrent.Callable<V>
•java.security.PrivilegedAction<T>
•java.util.Comparator<T>
•java.io.FileFilter
•java.nio.file.PathMatcher
•java.lang.reflect.InvocationHandler
•java.beans.PropertyChangeListener
•java.awt.event.ActionListener
•javax.swing.event.ChangeListener
21
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Attributes of Functional Interfaces
•Parameter types
•Return type
•Method type arguments
•Thrown exceptions
•An expressive, reifiable type name (possibly generic)
•An informal contract
22
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Shiny New Functional Interfaces*
•java.util.functions.Predicate<T>
•java.util.functions.Factory<T>
•java.util.functions.Block<T>
•java.util.functions.Mapper<T, R>
•java.util.functions.BinaryOperator<T>
23
* Names and concepts in libraries are still tentative
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
/** Creates an empty set. */
public interface SetFactory {
<T> Set<T> create();
}
/** Performs a blocking, interruptible action. */
public interface BlockingTask<T> {
<T> T run() throws InterruptedException;
}
Declare Your Own
24
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Target Typing
25
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
// Runnable: void run()
Runnable r =
() -> System.out.println(“hi”);
// Predicate<String>: boolean test(String arg)
Predicate<String> pred =
s -> s.length() < 100;
Assigning a Lambda to a Variable
26
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Object o =
() -> System.out.println(“hi”);
// Predicate<String>: boolean test(String arg)
Predicate<String> pred =
() -> System.out.println(“hi”);
Target Typing Errors
27
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
long[][] arr =
{ { 1, 2, 3 }, { 4, 5, 6 } };
List<? extends Number> nums =
Collections.emptyList();
Set<Map<String, Object>> maps =
new HashSet<>();
Target Typing in Java 7
28
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
class Thread {
public Thread(Runnable r) { ... }
}
// Runnable: void run()
new Thread(() -> System.out.println(“hi”));
Target Typing for Invocations
29
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
interface Stream<T> {
Stream<T> filter(Predicate<T> pred);
}
Stream<String> strings = ...;
// Predicate<T>: boolean test(T arg)
strings.filter(s -> s.length() < 100);
Target Typing for Invocations
30
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
<T> int m(Predicate<T> p);
int m(FileFilter f);
<S,T> int m(Mapper<S,T> m);
m(x -> x == null);
A Recipe for Disaster
(Or: A Recipe for Awesome)
31
•Target typing
•Overload resolution
•Type argument inference
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Object o =
(Runnable) () -> System.out.println(“hi”);
Runnable r =
condition() ? null : () -> System.gc();
Mapper<String, Runnable> m =
s -> () -> System.out.println(s);
Other Target Typing Contexts
32
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Method References
33
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
(x, y, z) -> Arrays.asList(x, y, z)
(str, i) -> str.substring(i)
() -> Thread.currentThread().dumpStack()
(s) -> new File(s)
Boilerplate Lambdas
34
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
(x, y, z) -> Arrays.asList(x, y, z)
Arrays::asList
(str, i) -> str.substring(i)
String::substring
() -> Thread.currentThread().dumpStack()
Thread.currentThread()::dumpStack
(s) -> new File(s)
File::new
Method (and Constructor) References
35
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Resolving a Method Reference
36
•Target type provides argument types
•Named method is searched for using those argument types
• Searching for an instance method, the first parameter is the receiver
•Return type must be compatible with target return
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Mapper<Byte, Set<Byte>> m1 = Collections::singleton;
// SetFactory: <T> Set<T> create()
SetFactory f2 = Collections::emptySet;
Mapper<Queue<Float>, Float> m2 = Queue::peek;
Factory<Set<String>> f3 = HashSet::new;
Method References & Generics
37
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Default Methods
38
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
New abstract methods: Bad
interface Widget {
double weight();
double volume();
double density();
}
New concrete methods: Good
abstract class Widget {
abstract double weight();
abstract double volume();
double density() {
return weight()/volume();
}
}
Evolving APIs
39
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
class Widgets {
static double density(Widget w) {
return w.weight()/w.volume();
}
}
Workaround: Garbage Classes
40
•Not really a class
•Non-idiomatic invocation syntax
•Non-virtual
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
interface Widget {
double weight();
double volume();
default double density() {
return weight()/volume();
}
}
Default Methods: Code in Interfaces
41
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Multiple Inheritance?
42
class C:
concrete m()
interface I:
default m()
class D
interface I:
default m()
interface J:
abstract m()
interface K
interface J:
default m()
interface K
class C
interface I:
default m()
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
interface Enumeration<E> extends Iterator<E> {
boolean hasMoreElements();
E nextElement();
default boolean hasNext() { return hasMoreElements(); }
default E next() { return getNext(); }
default void remove() { throw new UnsupportedOperationException(); }
default void forEachParallel(Block<T> b) { ... }
}
Evolving the Java Standard API
43
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Summary
44
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Goals for Project Lambda
45
•Make dramatic & necessary enhancements to the programming model
•Smooth some rough edges in the language
•Preserve compatibility
•Maintain the essence of the Java language
Thursday, November 8, 12
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
Learning More
•OpenJDK: openjdk.java.net/projects/lambda
•JSR 335: www.jcp.org/en/jsr/detail?id=335
•Me: daniel.smith@oracle.com
•Download it and try it out!
46
Thursday, November 8, 12

Más contenido relacionado

Destacado

How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaBoldRadius Solutions
 
Enabling CD in Enterprises with Testing
Enabling CD in Enterprises with TestingEnabling CD in Enterprises with Testing
Enabling CD in Enterprises with TestingAnand Bagmar
 
25 Examples of Native Analytics in Modern Products
25 Examples of Native Analytics in Modern Products25 Examples of Native Analytics in Modern Products
25 Examples of Native Analytics in Modern ProductsKeen
 
Harnessing The Power of CDNs
Harnessing The Power of CDNsHarnessing The Power of CDNs
Harnessing The Power of CDNsGurpreet Luthra
 
To Deploy or Not-To-Deploy - decide using TTA's Trend & Failure Analysis
To Deploy or Not-To-Deploy - decide using TTA's Trend & Failure AnalysisTo Deploy or Not-To-Deploy - decide using TTA's Trend & Failure Analysis
To Deploy or Not-To-Deploy - decide using TTA's Trend & Failure AnalysisAnand Bagmar
 
Как делать хорошие продукты (lean startup + customer development)
Как делать хорошие продукты (lean startup + customer development)Как делать хорошие продукты (lean startup + customer development)
Как делать хорошие продукты (lean startup + customer development)Artem Serdyuk
 

Destacado (7)

How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in Scala
 
Enabling CD in Enterprises with Testing
Enabling CD in Enterprises with TestingEnabling CD in Enterprises with Testing
Enabling CD in Enterprises with Testing
 
25 Examples of Native Analytics in Modern Products
25 Examples of Native Analytics in Modern Products25 Examples of Native Analytics in Modern Products
25 Examples of Native Analytics in Modern Products
 
Harnessing The Power of CDNs
Harnessing The Power of CDNsHarnessing The Power of CDNs
Harnessing The Power of CDNs
 
To Deploy or Not-To-Deploy - decide using TTA's Trend & Failure Analysis
To Deploy or Not-To-Deploy - decide using TTA's Trend & Failure AnalysisTo Deploy or Not-To-Deploy - decide using TTA's Trend & Failure Analysis
To Deploy or Not-To-Deploy - decide using TTA's Trend & Failure Analysis
 
Joshua Slayton
Joshua SlaytonJoshua Slayton
Joshua Slayton
 
Как делать хорошие продукты (lean startup + customer development)
Как делать хорошие продукты (lean startup + customer development)Как делать хорошие продукты (lean startup + customer development)
Как делать хорошие продукты (lean startup + customer development)
 

Más de C4Media

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoC4Media
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileC4Media
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020C4Media
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsC4Media
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No KeeperC4Media
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like OwnersC4Media
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaC4Media
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideC4Media
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDC4Media
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine LearningC4Media
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at SpeedC4Media
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsC4Media
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsC4Media
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerC4Media
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleC4Media
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeC4Media
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereC4Media
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing ForC4Media
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data EngineeringC4Media
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
 

Más de C4Media (20)

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live Video
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy Mobile
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java Applications
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No Keeper
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like Owners
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CD
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep Systems
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.js
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix Scale
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home Everywhere
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing For
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 

Último

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
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
 
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
 
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
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
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
 
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
 
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
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Project Lambda in Java SE 8

  • 1. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 131 Project Lambda in Java SE 8 Daniel Smith Java Language Designer Thursday, November 8, 12
  • 2. InfoQ.com: News & Community Site • 750,000 unique visitors/month • Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese) • Post content from our QCon conferences • News 15-20 / week • Articles 3-4 / week • Presentations (videos) 12-15 / week • Interviews 2-3 / week • Books 1 / month Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations /Project-Lambda-Java-SE-8-SF
  • 3. Presented at QCon San Francisco www.qconsf.com Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide
  • 4. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 132 The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Thursday, November 8, 12
  • 5. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 The Java Programming Language •Around 9,000,000 developers worldwide •17 years old •4 major revisions (1996, 1997, 2004, 2013...) •[Insert staggering number] of companies very heavily invested •Formally standardized and evolved via community 3 Thursday, November 8, 12
  • 6. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Evolving a Major Language •Adapting to change •Righting what’s wrong •Maintaining compatibility •Preserving the core 4 Thursday, November 8, 12
  • 7. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 135 Project Lambda: Function Values in Java Thursday, November 8, 12
  • 8. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Object subclass: Widget [ draw: canvas [ ... ] click [ ... ] ] gui add:(Widget new). (define f (lambda (x) (* x x))) (map nums f) Code as Data 6 Thursday, November 8, 12
  • 9. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 interface Runnable { void run(); } Thread hello = new Thread(new Runnable() { public void run() { System.out.println(“Hello, world!”); } }); Status Quo in Java 1.1 7 Thursday, November 8, 12
  • 10. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 interface Predicate<T> { boolean accept(T arg); } lines.removeAll(new Predicate<String>() { public boolean accept(String line) { return line.startsWith(“#”); } }); Status Quo in Java 5 8 Thursday, November 8, 12
  • 11. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 interface Predicate<T> { boolean accept(T arg); } lines.removeAll(line -> line.startsWith(“#”)); What We Wish It Looked Like 9 Thursday, November 8, 12
  • 12. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Why Functions in Java? Adapting to Change 10 •Widely-adopted programming style • 1995: functions-as-values is too hard to understand • Now: almost everybody has them (even C++) •Physical constraints cause changing models • 1995: sequential execution, mutation • Today: concurrency, immutability •A gentle push in the right direction Thursday, November 8, 12
  • 13. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Why Functions in Java? Better Libraries 11 •Lots of applications... •Our priorities: • Collections • Concurrency public class ForkBlur extends RecursiveAction { private int[] mSource; private int mStart; private int mLength; private int[] mDestination; public ForkBlur(int[] src, int start, int length, int[] dst) { mSource = src; mStart = start; mLength = length; mDestination = dst; } // Average pixels from source, write results into destination. protected void computeDirectly() { for (int index = mStart; index < mStart + mLength; index++) { mDestination[index] = blur(index, mSource); } } protected static int sThreshold = 10000; protected void compute() { if (mLength < sThreshold) { computeDirectly(); return; } int split = mLength / 2; invokeAll(new ForkBlur(mSource, mStart, split, mDestination), new ForkBlur(mSource, mStart + split, mLength - split, mDestination)); } } Thursday, November 8, 12
  • 14. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Brief History •1997: Odersky/Wadler experimental “Pizza” work •1997: Java 1.1 with anonymous classes •2006-2008: Vigorous community debate •2009: OpenJDK Project Lambda formed •2010: JSR 335 filed 12 Thursday, November 8, 12
  • 15. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1313 Java 8 Language Concepts & Features  Lambda expressions  Functional interfaces  Target typing  Method references  Default methods Thursday, November 8, 12
  • 16. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Lambda Expressions 14 Thursday, November 8, 12
  • 17. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 widget -> { if (flag) widget.poke(); else widget.prod(); } (int x, int y) -> { assert x < y; return x*y; } x -> x+1 (s,i) -> s.substring(0,i) (Integer i) -> list.add(i) () -> System.out.print(“x”) cond -> cond ? 23 : 57 Lambda Expressions 15 Thursday, November 8, 12
  • 18. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 void cut(List<String> l, int len) { l.updateAll(s -> s.substring(0, len)); } Variable Capture 16 •Lambdas can refer to variables declared outside the body •These variables can be final or “effectively final” • Works for anonymous classes, too Thursday, November 8, 12
  • 19. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Meaning of Names in Lambdas 17 •Anonymous classes introduce a new “level” of scope • ‘this’ means the inner class instance • ‘ClassName.this’ is used to get to the enclosing class instance • Inherited names can shadow outer-scope names •Lambdas reside in the same “level” as the enclosing context • this refers to the enclosing class • No new names are inherited • Like local variables, parameter names can’t shadow other locals Thursday, November 8, 12
  • 20. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Functional Interfaces 18 Thursday, November 8, 12
  • 21. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 String -> int (String, int, boolean) -> List<? extends Integer> (String, Number) -> Class<?> throws IOException Function Types in Java? 19 Thursday, November 8, 12
  • 22. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Function Types in Java: Functional Interfaces 20 Thursday, November 8, 12
  • 23. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Common Existing Functional Interfaces •java.lang.Runnable •java.util.concurrent.Callable<V> •java.security.PrivilegedAction<T> •java.util.Comparator<T> •java.io.FileFilter •java.nio.file.PathMatcher •java.lang.reflect.InvocationHandler •java.beans.PropertyChangeListener •java.awt.event.ActionListener •javax.swing.event.ChangeListener 21 Thursday, November 8, 12
  • 24. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Attributes of Functional Interfaces •Parameter types •Return type •Method type arguments •Thrown exceptions •An expressive, reifiable type name (possibly generic) •An informal contract 22 Thursday, November 8, 12
  • 25. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Shiny New Functional Interfaces* •java.util.functions.Predicate<T> •java.util.functions.Factory<T> •java.util.functions.Block<T> •java.util.functions.Mapper<T, R> •java.util.functions.BinaryOperator<T> 23 * Names and concepts in libraries are still tentative Thursday, November 8, 12
  • 26. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 /** Creates an empty set. */ public interface SetFactory { <T> Set<T> create(); } /** Performs a blocking, interruptible action. */ public interface BlockingTask<T> { <T> T run() throws InterruptedException; } Declare Your Own 24 Thursday, November 8, 12
  • 27. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Target Typing 25 Thursday, November 8, 12
  • 28. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 // Runnable: void run() Runnable r = () -> System.out.println(“hi”); // Predicate<String>: boolean test(String arg) Predicate<String> pred = s -> s.length() < 100; Assigning a Lambda to a Variable 26 Thursday, November 8, 12
  • 29. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Object o = () -> System.out.println(“hi”); // Predicate<String>: boolean test(String arg) Predicate<String> pred = () -> System.out.println(“hi”); Target Typing Errors 27 Thursday, November 8, 12
  • 30. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 long[][] arr = { { 1, 2, 3 }, { 4, 5, 6 } }; List<? extends Number> nums = Collections.emptyList(); Set<Map<String, Object>> maps = new HashSet<>(); Target Typing in Java 7 28 Thursday, November 8, 12
  • 31. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 class Thread { public Thread(Runnable r) { ... } } // Runnable: void run() new Thread(() -> System.out.println(“hi”)); Target Typing for Invocations 29 Thursday, November 8, 12
  • 32. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 interface Stream<T> { Stream<T> filter(Predicate<T> pred); } Stream<String> strings = ...; // Predicate<T>: boolean test(T arg) strings.filter(s -> s.length() < 100); Target Typing for Invocations 30 Thursday, November 8, 12
  • 33. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 <T> int m(Predicate<T> p); int m(FileFilter f); <S,T> int m(Mapper<S,T> m); m(x -> x == null); A Recipe for Disaster (Or: A Recipe for Awesome) 31 •Target typing •Overload resolution •Type argument inference Thursday, November 8, 12
  • 34. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Object o = (Runnable) () -> System.out.println(“hi”); Runnable r = condition() ? null : () -> System.gc(); Mapper<String, Runnable> m = s -> () -> System.out.println(s); Other Target Typing Contexts 32 Thursday, November 8, 12
  • 35. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Method References 33 Thursday, November 8, 12
  • 36. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 (x, y, z) -> Arrays.asList(x, y, z) (str, i) -> str.substring(i) () -> Thread.currentThread().dumpStack() (s) -> new File(s) Boilerplate Lambdas 34 Thursday, November 8, 12
  • 37. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 (x, y, z) -> Arrays.asList(x, y, z) Arrays::asList (str, i) -> str.substring(i) String::substring () -> Thread.currentThread().dumpStack() Thread.currentThread()::dumpStack (s) -> new File(s) File::new Method (and Constructor) References 35 Thursday, November 8, 12
  • 38. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Resolving a Method Reference 36 •Target type provides argument types •Named method is searched for using those argument types • Searching for an instance method, the first parameter is the receiver •Return type must be compatible with target return Thursday, November 8, 12
  • 39. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Mapper<Byte, Set<Byte>> m1 = Collections::singleton; // SetFactory: <T> Set<T> create() SetFactory f2 = Collections::emptySet; Mapper<Queue<Float>, Float> m2 = Queue::peek; Factory<Set<String>> f3 = HashSet::new; Method References & Generics 37 Thursday, November 8, 12
  • 40. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Default Methods 38 Thursday, November 8, 12
  • 41. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 New abstract methods: Bad interface Widget { double weight(); double volume(); double density(); } New concrete methods: Good abstract class Widget { abstract double weight(); abstract double volume(); double density() { return weight()/volume(); } } Evolving APIs 39 Thursday, November 8, 12
  • 42. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 class Widgets { static double density(Widget w) { return w.weight()/w.volume(); } } Workaround: Garbage Classes 40 •Not really a class •Non-idiomatic invocation syntax •Non-virtual Thursday, November 8, 12
  • 43. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 interface Widget { double weight(); double volume(); default double density() { return weight()/volume(); } } Default Methods: Code in Interfaces 41 Thursday, November 8, 12
  • 44. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Multiple Inheritance? 42 class C: concrete m() interface I: default m() class D interface I: default m() interface J: abstract m() interface K interface J: default m() interface K class C interface I: default m() Thursday, November 8, 12
  • 45. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 interface Enumeration<E> extends Iterator<E> { boolean hasMoreElements(); E nextElement(); default boolean hasNext() { return hasMoreElements(); } default E next() { return getNext(); } default void remove() { throw new UnsupportedOperationException(); } default void forEachParallel(Block<T> b) { ... } } Evolving the Java Standard API 43 Thursday, November 8, 12
  • 46. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Summary 44 Thursday, November 8, 12
  • 47. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Goals for Project Lambda 45 •Make dramatic & necessary enhancements to the programming model •Smooth some rough edges in the language •Preserve compatibility •Maintain the essence of the Java language Thursday, November 8, 12
  • 48. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 Learning More •OpenJDK: openjdk.java.net/projects/lambda •JSR 335: www.jcp.org/en/jsr/detail?id=335 •Me: daniel.smith@oracle.com •Download it and try it out! 46 Thursday, November 8, 12