SlideShare une entreprise Scribd logo
1  sur  52
Télécharger pour lire hors ligne
Evolution of a Language Feature
Dan Heidinga, J9 VM Interpreter Lead
Daniel_Heidinga@ca.ibm.com
@DanHeidinga
26 October 2015
Invokedynamic
Brian Goetz, Java Language Architect
Oracle
Who am I?
 I've been involved with virtual machine development at IBM
since 2007 and am now the J9 Virtual Machine Team Lead.
J9 is IBM's independent implementation of the JVM.
 I've represented IBM on both the JSR 292 ('invokedynamic')
and JSR 335 ('lambda') expert groups and lead J9's
implementation of both JSRs.
 I’ve also maintain the bytecode verifier and deal with various
other parts of the runtime.
2
Who am I?
 Brian Goetz is the Java Language Architect at Oracle, and is
one of the leading authorities on the Java platform.
 He is the author of the very successful 'Java Concurrency in
Practice', and has published over 75 articles on software
development.
 He was the specification lead for JSR-335 (Lambda
Expressions for the Java Language) and has served on
numerous other JCP Expert Groups.
3
Important disclaimers
 THE INFORMATION CONTAINED IN THIS PRESENTATION IS PROVIDED FOR INFORMATIONAL PURPOSES ONLY.
 WHILST EFFORTS WERE MADE TO VERIFY THE COMPLETENESS AND ACCURACY OF THE INFORMATION
CONTAINED IN THIS PRESENTATION, IT IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED.
 ALL PERFORMANCE DATA INCLUDED IN THIS PRESENTATION HAVE BEEN GATHERED IN A CONTROLLED
ENVIRONMENT. YOUR OWN TEST RESULTS MAY VARY BASED ON HARDWARE, SOFTWARE OR
INFRASTRUCTURE DIFFERENCES.
 ALL DATA INCLUDED IN THIS PRESENTATION ARE MEANT TO BE USED ONLY AS A GUIDE.
 IN ADDITION, THE INFORMATION CONTAINED IN THIS PRESENTATION IS BASED ON IBM’S CURRENT
PRODUCT PLANS AND STRATEGY, WHICH ARE SUBJECT TO CHANGE BY IBM, WITHOUT NOTICE.
 IBM AND ITS AFFILIATED COMPANIES SHALL NOT BE RESPONSIBLE FOR ANY DAMAGES ARISING OUT
OF THE USE OF, OR OTHERWISE RELATED TO, THIS PRESENTATION OR ANY OTHER DOCUMENTATION.
 NOTHING CONTAINED IN THIS PRESENTATION IS INTENDED TO, OR SHALL HAVE THE EFFECT OF:
– CREATING ANY WARRANT OR REPRESENTATION FROM IBM, ITS AFFILIATED COMPANIES OR ITS
OR THEIR SUPPLIERS AND/OR LICENSORS
4
Danger: highly technical talk!
 This talk assumes you’re familiar with:
– JVM bytecode set
– java.lang.invoke.MethodHandle and related classes
– invokedynamic
5
Full bleed images preferred
Text over top of full bleed images would be in white or a color from the color palette that
would offer good contrast. Also, colored text in Arial Bold would have greater impact.
JVM Specification, first edition
7
JVM Specification, first edition
8
The JVM: a highly tuned performance machine
https://commons.wikimedia.org/wiki/File:Fernando_Alonso_2010_Jerez_test_14.jpg9
It’s fastest when you stay on the path
JVM optimized and tuned for the Java language.
As long as the language maps cleanly to Java’s semantics, good perf is likely
10
JVM invoke instructions
 Prior to Java 7, there were 4 bytecodes to invoke methods:
– invokespecial: constructors, super calls, private methods
– invokevirtual: receiver based selection of instance methods
– invokestatic: static methods
– invokeinterface: interface based selection of instance methods
 The semantics are tightly defined by the JVM spec
11
12
Resolution
Access checking
Type constraints
Selection
Ruby fib
 Show Ruby fib and outline why it’s not the same as the Java version
13
def fib(x)
if x < 2
return x
end
return fib(x-2) + fib(x-1)
end
Ruby fib
 6 method sends for Ruby vs 2 for Java
14
def fib(x)
if x < 2
return x
end
return fib(x-2) + fib(x-1)
end
JRuby: ~1.6 implementation
15
CachingCallSite DynamicMethod
@JRubyMethod(name = "+")
public IRubyObject op_plus(ThreadContext ctx, IRubyObject other)
{
if (other instanceof RubyFixnum) {
return addFixnum(ctx, (RubyFixnum)other);
}
return addOther(ctx, other);
}
Second class performance citizen: Dynamic languages
 Simulation overheads:
– Inlining depth limits
– Inlining bytecode size limits
– Reflection overhead
– Non-inlinable caching / Hashtable lookups
– Type mismatches: sharp types vs IRubyObject
 Complexity
– Generating invokers at build time based on annotations
– Need to ensure the cache is correct
16
JVM Specification, first edition
17
Birth of JSR 292 EG
18
New JVM instruction, invokedynamic, designed to support the
implementation of dynamically typed object oriented languages.
… investigate support for hotswapping
The problem: linkage + typing
 JVM invoke instructions are tightly tied to Java
– Linkage must match the JVM rules
 My language uses different dispatch rules
– Metaclass
– Multiple dispatch
– Mixins
 User’s need to control the linkage
19
https://en.wikipedia.org/wiki/Burr_puzzle#/media/File:SixPartWoodKnot.jpg
RestartMethodException & VM method cache
 Invokedynamic
– like invokevirtual except:
 arguments not required to match the method’s signature
 support for “doesNotUnderstand” handler
– recursive lookup for method exactly matching descriptor
 else call handler, which can:
 implement the method & return result
 pick a method and return it (via RestartMethodException)
> VM can cache the “restart” method
20
From InvokeDynamic to target method
Invokedynamic Target method
21
User supplied
logic
 Tell the VM what
method to link to
From InvokeDynamic to target method
Invokedynamic
Static data:
Caller
Method name
Descriptor
Other data
Target method
22
User supplied
logic
 Tell the VM what
method to link to
BootstrapMethod
From InvokeDynamic to target method
Invokedynamic
java.lang.invoke.CallSite
Target method
23
User supplied
logic
 Tell the VM what
method to link to
BootstrapMethod
From InvokeDynamic to target method
Invokedynamic
java.lang.invoke.CallSite
Target method
24
User supplied
logic
 Tell the VM what
method to link to
BootstrapMethod
From InvokeDynamic to target method
Invokedynamic Target method
25
java.lang.invoke.CallSite
Indy is permanently linked to the CallSite (1 time)
Invocation of target method can occur many times
Anatomy of a CallSite
26
CallSite
type
target
MethodType
(String)V
MethodHandle
link(String)V
Anatomy of a CallSite
27
CallSite
type
target
MethodType
(String)V
MethodHandle
link(String)V
The link() handle does two things:
1. It sets CallSite target
2. Completes the call
Anatomy of a CallSite
28
CallSite
type
target
MethodType
(String)V
MethodHandle
link(String)V
GuardWithTest
test
target
fallback
MethodHandle
Guard()boolean
MethodHandle
Method(String)V
Invokedynamic: bytecode factory
 Lazy constants
 New semantics
 New bytecodes
 All these and more can be emulated using invokedynamic
– Bootstrap Method to link the CallSite
– Java code that implements the new operation
– Really the ultimate bytecode emulation tool
29
Interface injection
A Class implements all the methods for an interface
Doesn’t declare it implements it
– How can we allow the interface invocation to proceed?
30
Foo foo = new Foo();
if (foo instanceof Injected) {
Injected i = (Injected) foo;
System.out.println(i.m());
}
instanceof
checkcast
invokeinterface
Interface injection: 3 Bootstrap Methods
31
Interface injection: 2 helpers
32
Interface injection: bytecode
33
0: new #14 // class Foo
3: dup
4: invokespecial #15 // Method Foo."<init>":()V
7: astore_1
8: aload_1
9: invokedynamic #28, 0 // InvokeDynamic #0:instanceof:(LObject;)Z
14: ifeq 36
17: aload_1
18: invokedynamic #36, 0 // InvokeDynamic #1:checkcast:(LObject;)LInjected;
23: astore_2
24: getstatic #42 // Field System.out:LPrintStream;
27: aload_2
28: invokedynamic #50, 0 // InvokeDynamic #2:m:(LObject;)LString;
33: invokevirtual #56 // Method PrintStream.println:(LString;)V
36: return
BootstrapMethods:
0: #22 invokestatic Runtime.instanceOfBSM:(LLookup;LString;LMethodType;LClass;)LCallSite;
Method arguments:
#24 Injected
1: #32 invokestatic Runtime.checkcastBSM:(LLookup;LString;LMethodType;LClass;)LCallSite;
Method arguments:
#24 Injected
2: #46 invokestatic
Runtime.invokeinterfaceBSM:(LLookup;LString;LMethodType;Ljava/lang/Class;)LCallSite;
Method arguments:
#24 Injected
[jsr-292-eg] our package name 01/06/2011
 Invokedynamic is more than dynamic languages!
 Lambda can be built on top of invokedynamic and MethodHandles
 (Painfully) renamed the package from java.dyn to java.lang.invoke at development cutoff
34
Birth of JSR 292 EG
35
New JVM instruction, invokedynamic, designed to support the
implementation of dynamically typed object oriented languages.
… investigate support for hotswapping
Wait, what is a dyn language anyway?
Static Dynamic
36
Wait, what is a dyn language anyway?
Static Dynamic
37
Compile
time
Runtime
Wait, what is a dyn language anyway?
Static Dynamic
38
Compile
time
Runtime
Wait, what is a dyn language anyway?
Static
Typing
Dispatch
Dynamic
Binding
(Un)Loading
39
Its not just for dynamic languages anymore
 Java 8 gave us Lambda expressions
– But how do we compile this lambda?
40
Predicate<Person> pred = p -> p.age < minAge;
Its not just for dynamic languages anymore
 So, if indy is for dynamic languages, why is the Java compiler using it?
– All the types involved are static
– We can use indy to give us a dynamic code generation strategy
 Generate inner classes?
 Use method handles?
 Use dynamic proxies?
 Use VM-private APIs for constructing objects?
 Indy lets us turn this choice into a pure implementation detail
– Separate from the binary representation
41
Desugaring lambdas to methods
 First, we desugar the lambda to a method
– Signature matches functional interface method
– Plus captured arguments prepended
– Simplest lambdas desugar to static methods
 But some need access to receiver, and so are instance methods
42
Predicate<Person> pred = p -> p.age < minAge;
private static boolean lambda$1(int minAge, Person p) {
return p.age < minAge;
}
Its not just for dynamic languages anymore
 We use indy to embed a recipe for constructing a lambda, including
– The desugared implementation method (static)
– The functional interface we are converting to (static)
– Additional metadata, such as serialization information (static)
– Values captured from the lexical scope (dynamic)
 The capture site is called the lambda factory
– Invoked with indy, returns an instance of the desired functional interface
– Subsequent captures bypass the (slow) linkage path
43
Factories and metafactories
 We generate an indy call site which, when called, returns the lambda
– This is the lambda factory
– Bootstrap for the lambda factory
selects the translation strategy
 Bootstrap is called the lambda metafactory
 Part of Java runtime
– Captured args passed
to lambda factory
44
list.removeIf(p -> p.age < minAge);
private static boolean lambda$1(int minAge, Person p) {
return p.getAge() >= minAge;
}
Predicate $p = indy[bootstrap=LambdaMetafactory,
staticargs=[Predicate, lambda$1],
dynargs=[minAge])
list.removeIf($p);
Full bleed images preferred
Text over top of full bleed images would be in white or a color from the color palette that
would offer good contrast. Also, colored text in Arial Bold would have greater impact.
Optimized String concat (JEP tbd)
46
String m(String a, int b) {
return a + "(" + b + ")";
}
java.lang.String m(java.lang.String, int);
0: new #2 // class StringBuilder
3: dup
4: invokespecial #3 // Method StringBuilder.<init>:()V
7: aload_1
8: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
11: ldc #5 // String (
13: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
16: iload_2
17: invokevirtual #6 // Method StringBuilder.append:(I)LStringBuilder;
20: ldc #7 // String )
22: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
25: invokevirtual #8 // Method StringBuilder.toString:()LString;
28: areturn
http://openjdk.java.net/jeps/8085796
Optimized String concat (JEP tbd)
47
String m(String a, int b) {
return a + "(" + b + ")";
}
java.lang.String m(java.lang.String, int);
0: aload_1
1: ldc #2 // String (
3: iload_2
4: ldc #3 // String )
6: invokedynamic #4, 0
// InvokeDynamic #0:stringConcat:(LString;LString;ILString;)LString;
11: areturn
BootstrapMethods:
0: #19 invokestatic StringConcatFactory.stringConcat:
(LMethodHandles$Lookup;LString;LMethodType;LString;[LObject;)LCallSite;
http://openjdk.java.net/jeps/8085796
48
Invoking Specialized Generic Static Methods
 We need to capture the type argument at the callsite.
 How does m access the type information at run-time?
class C {
static <any T> T m(T i) {…}
}
int i = C.<int>m(3);
 Embed specialized type information in the invokedynamic Callsite
Invoking Specialized Static Methods (cont’d)
7: iconst_3
8: invokedynamic #4, 0 // InvokeDynamic #0:m:(LFoo;I)V
BootstrapMethods:
0: #26 invokestatic GenericMethodSpecializer.metafactory:
(LMethodHandles$Lookup;LString;LMethodType;[LObject;)LCallSite;
Method arguments:
#27 LC;
#28 invokevirtual C.m:(LObject;)V
#29 I
51
52
Legal Notice
IBM and the IBM logo are trademarks or registered trademarks of IBM Corporation, in the United States, other
countries or both.
Java and all Java-based marks, among others, are trademarks or registered trademarks of Oracle in the United
States, other countries or both.
Other company, product and service names may be trademarks or service marks of others.
THE INFORMATION DISCUSSED IN THIS PRESENTATION IS PROVIDED FOR INFORMATIONAL
PURPOSES ONLY. WHILE EFFORTS WERE MADE TO VERIFY THE COMPLETENESS AND
ACCURACY OF THE INFORMATION, IT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, AND IBM SHALL NOT BE RESPONSIBLE FOR ANY DAMAGES ARISING OUT
OF THE USE OF, OR OTHERWISE RELATED TO, SUCH INFORMATION. ANY INFORMATION
CONCERNING IBM'S PRODUCT PLANS OR STRATEGY IS SUBJECT TO CHANGE BY IBM WITHOUT
NOTICE.

Contenu connexe

Tendances

Extreme Interview Questions
Extreme Interview QuestionsExtreme Interview Questions
Extreme Interview QuestionsEhtisham Ali
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIwhite paper
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java BasicsFayis-QA
 
Model-Driven Development in the context of Software Product Lines
Model-Driven Development in the context of Software Product LinesModel-Driven Development in the context of Software Product Lines
Model-Driven Development in the context of Software Product LinesMarkus Voelter
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java BasicsVicter Paul
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, androidi i
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeAlain Leon
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java CertificationVskills
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaHoang Nguyen
 
Jfokus 2016 - A JVMs Journey into Polyglot Runtimes
Jfokus 2016 - A JVMs Journey into Polyglot RuntimesJfokus 2016 - A JVMs Journey into Polyglot Runtimes
Jfokus 2016 - A JVMs Journey into Polyglot RuntimesCharlie Gracie
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and BytecodeYoav Avrahami
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introductionjyoti_lakhani
 

Tendances (20)

Chapter 1 :
Chapter 1 : Chapter 1 :
Chapter 1 :
 
Extreme Interview Questions
Extreme Interview QuestionsExtreme Interview Questions
Extreme Interview Questions
 
109842496 jni
109842496 jni109842496 jni
109842496 jni
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
 
Java interview question
Java interview questionJava interview question
Java interview question
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
Model-Driven Development in the context of Software Product Lines
Model-Driven Development in the context of Software Product LinesModel-Driven Development in the context of Software Product Lines
Model-Driven Development in the context of Software Product Lines
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
 
Best interview questions
Best interview questionsBest interview questions
Best interview questions
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik Bytecode
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 
Java &amp; advanced java
Java &amp; advanced javaJava &amp; advanced java
Java &amp; advanced java
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Jfokus 2016 - A JVMs Journey into Polyglot Runtimes
Jfokus 2016 - A JVMs Journey into Polyglot RuntimesJfokus 2016 - A JVMs Journey into Polyglot Runtimes
Jfokus 2016 - A JVMs Journey into Polyglot Runtimes
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Java platform
Java platformJava platform
Java platform
 

En vedette

Merits of the Global Portfolio
Merits of the Global PortfolioMerits of the Global Portfolio
Merits of the Global PortfolioGerstein Fisher
 
Bond Investing Strategy (Part 1)
Bond Investing Strategy (Part 1)Bond Investing Strategy (Part 1)
Bond Investing Strategy (Part 1)Gerstein Fisher
 
Types of Technology
Types of TechnologyTypes of Technology
Types of TechnologyKrice92
 
Knowledge from health registries, cohorts, and biobanks stein emilvollset
Knowledge from health registries, cohorts, and biobanks stein emilvollsetKnowledge from health registries, cohorts, and biobanks stein emilvollset
Knowledge from health registries, cohorts, and biobanks stein emilvollsetEPINOR
 
IMAGINE A WORLD DEVOID OF PLANTS
IMAGINE A WORLD DEVOID OF PLANTSIMAGINE A WORLD DEVOID OF PLANTS
IMAGINE A WORLD DEVOID OF PLANTSOkpalaugo ME'buEZE
 
Nguy cơ tai biến tăng cao vào mùa đông
Nguy cơ tai biến tăng cao vào mùa đôngNguy cơ tai biến tăng cao vào mùa đông
Nguy cơ tai biến tăng cao vào mùa đôngerin432
 
Measuring the Investment Tax Drag
Measuring the Investment Tax DragMeasuring the Investment Tax Drag
Measuring the Investment Tax DragGerstein Fisher
 
Maintaining the Purchasing Power of Portfolios
Maintaining the Purchasing Power of PortfoliosMaintaining the Purchasing Power of Portfolios
Maintaining the Purchasing Power of PortfoliosGerstein Fisher
 
Enterprising through promoting familipreneurship for sustainable poverty redu...
Enterprising through promoting familipreneurship for sustainable poverty redu...Enterprising through promoting familipreneurship for sustainable poverty redu...
Enterprising through promoting familipreneurship for sustainable poverty redu...Mijan Rahman
 
Three integration implementation options
Three integration implementation optionsThree integration implementation options
Three integration implementation options4Thought Marketing
 
Measuring the Cost of Investor Behavior
Measuring the Cost of Investor BehaviorMeasuring the Cost of Investor Behavior
Measuring the Cost of Investor BehaviorGerstein Fisher
 
Inflation and the Long-Term Investor
Inflation and the Long-Term InvestorInflation and the Long-Term Investor
Inflation and the Long-Term InvestorGerstein Fisher
 

En vedette (15)

Merits of the Global Portfolio
Merits of the Global PortfolioMerits of the Global Portfolio
Merits of the Global Portfolio
 
Bond Investing Strategy (Part 1)
Bond Investing Strategy (Part 1)Bond Investing Strategy (Part 1)
Bond Investing Strategy (Part 1)
 
Types of Technology
Types of TechnologyTypes of Technology
Types of Technology
 
Knowledge from health registries, cohorts, and biobanks stein emilvollset
Knowledge from health registries, cohorts, and biobanks stein emilvollsetKnowledge from health registries, cohorts, and biobanks stein emilvollset
Knowledge from health registries, cohorts, and biobanks stein emilvollset
 
THE GLORIA
THE GLORIATHE GLORIA
THE GLORIA
 
Pompano Beach Branch
Pompano Beach BranchPompano Beach Branch
Pompano Beach Branch
 
IMAGINE A WORLD DEVOID OF PLANTS
IMAGINE A WORLD DEVOID OF PLANTSIMAGINE A WORLD DEVOID OF PLANTS
IMAGINE A WORLD DEVOID OF PLANTS
 
Nguy cơ tai biến tăng cao vào mùa đông
Nguy cơ tai biến tăng cao vào mùa đôngNguy cơ tai biến tăng cao vào mùa đông
Nguy cơ tai biến tăng cao vào mùa đông
 
Measuring the Investment Tax Drag
Measuring the Investment Tax DragMeasuring the Investment Tax Drag
Measuring the Investment Tax Drag
 
Maintaining the Purchasing Power of Portfolios
Maintaining the Purchasing Power of PortfoliosMaintaining the Purchasing Power of Portfolios
Maintaining the Purchasing Power of Portfolios
 
Enterprising through promoting familipreneurship for sustainable poverty redu...
Enterprising through promoting familipreneurship for sustainable poverty redu...Enterprising through promoting familipreneurship for sustainable poverty redu...
Enterprising through promoting familipreneurship for sustainable poverty redu...
 
Three integration implementation options
Three integration implementation optionsThree integration implementation options
Three integration implementation options
 
Measuring the Cost of Investor Behavior
Measuring the Cost of Investor BehaviorMeasuring the Cost of Investor Behavior
Measuring the Cost of Investor Behavior
 
Data Health Check
Data Health Check Data Health Check
Data Health Check
 
Inflation and the Long-Term Investor
Inflation and the Long-Term InvestorInflation and the Long-Term Investor
Inflation and the Long-Term Investor
 

Similaire à invokedynamic: Evolution of a Language Feature

JavaOne2015-What's in an Object?
JavaOne2015-What's in an Object?JavaOne2015-What's in an Object?
JavaOne2015-What's in an Object?Charlie Gracie
 
#JavaOne What's in an object?
#JavaOne What's in an object?#JavaOne What's in an object?
#JavaOne What's in an object?Charlie Gracie
 
Java performance tuning
Java performance tuningJava performance tuning
Java performance tuningJerry Kurian
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Mr. Akaash
 
BP203 limitless languages
BP203 limitless languagesBP203 limitless languages
BP203 limitless languagesMark Myers
 
Ijaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinderIjaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinderijaprr_editor
 
Apache Big Data Europe 2016
Apache Big Data Europe 2016Apache Big Data Europe 2016
Apache Big Data Europe 2016Tim Ellison
 
JavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVMJavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVMPaulThwaite
 
QCon Shanghai: Trends in Application Development
QCon Shanghai: Trends in Application DevelopmentQCon Shanghai: Trends in Application Development
QCon Shanghai: Trends in Application DevelopmentChris Bailey
 
JRuby in Java Projects
JRuby in Java ProjectsJRuby in Java Projects
JRuby in Java Projectsjazzman1980
 
Extension and Evolution
Extension and EvolutionExtension and Evolution
Extension and EvolutionEelco Visser
 
01 Introduction to programming
01 Introduction to programming01 Introduction to programming
01 Introduction to programmingmaznabili
 
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.J On The Beach
 
(Costless) Software Abstractions for Parallel Architectures
(Costless) Software Abstractions for Parallel Architectures(Costless) Software Abstractions for Parallel Architectures
(Costless) Software Abstractions for Parallel ArchitecturesJoel Falcou
 

Similaire à invokedynamic: Evolution of a Language Feature (20)

JavaOne2015-What's in an Object?
JavaOne2015-What's in an Object?JavaOne2015-What's in an Object?
JavaOne2015-What's in an Object?
 
#JavaOne What's in an object?
#JavaOne What's in an object?#JavaOne What's in an object?
#JavaOne What's in an object?
 
Java performance tuning
Java performance tuningJava performance tuning
Java performance tuning
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
BP203 limitless languages
BP203 limitless languagesBP203 limitless languages
BP203 limitless languages
 
Ijaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinderIjaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinder
 
Apache Big Data Europe 2016
Apache Big Data Europe 2016Apache Big Data Europe 2016
Apache Big Data Europe 2016
 
Introduction to Programming Lesson 01
Introduction to Programming Lesson 01Introduction to Programming Lesson 01
Introduction to Programming Lesson 01
 
JavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVMJavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVM
 
Java1 in mumbai
Java1 in mumbaiJava1 in mumbai
Java1 in mumbai
 
Java basic
Java basicJava basic
Java basic
 
Java By Sai NagaVenkata BuchiBabu Manepalli
Java By Sai NagaVenkata BuchiBabu ManepalliJava By Sai NagaVenkata BuchiBabu Manepalli
Java By Sai NagaVenkata BuchiBabu Manepalli
 
Java By Sai NagaVenkata BuchiBabu Manepalli
Java By Sai NagaVenkata BuchiBabu ManepalliJava By Sai NagaVenkata BuchiBabu Manepalli
Java By Sai NagaVenkata BuchiBabu Manepalli
 
QCon Shanghai: Trends in Application Development
QCon Shanghai: Trends in Application DevelopmentQCon Shanghai: Trends in Application Development
QCon Shanghai: Trends in Application Development
 
JRuby in Java Projects
JRuby in Java ProjectsJRuby in Java Projects
JRuby in Java Projects
 
Extension and Evolution
Extension and EvolutionExtension and Evolution
Extension and Evolution
 
01 Introduction to programming
01 Introduction to programming01 Introduction to programming
01 Introduction to programming
 
Intro to java
Intro to javaIntro to java
Intro to java
 
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
 
(Costless) Software Abstractions for Parallel Architectures
(Costless) Software Abstractions for Parallel Architectures(Costless) Software Abstractions for Parallel Architectures
(Costless) Software Abstractions for Parallel Architectures
 

Dernier

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"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
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
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
 
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
 
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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"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
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
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
 
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
 
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
 

Dernier (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"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
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
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
 
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
 
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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"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
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
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
 
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.
 
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
 

invokedynamic: Evolution of a Language Feature

  • 1. Evolution of a Language Feature Dan Heidinga, J9 VM Interpreter Lead Daniel_Heidinga@ca.ibm.com @DanHeidinga 26 October 2015 Invokedynamic Brian Goetz, Java Language Architect Oracle
  • 2. Who am I?  I've been involved with virtual machine development at IBM since 2007 and am now the J9 Virtual Machine Team Lead. J9 is IBM's independent implementation of the JVM.  I've represented IBM on both the JSR 292 ('invokedynamic') and JSR 335 ('lambda') expert groups and lead J9's implementation of both JSRs.  I’ve also maintain the bytecode verifier and deal with various other parts of the runtime. 2
  • 3. Who am I?  Brian Goetz is the Java Language Architect at Oracle, and is one of the leading authorities on the Java platform.  He is the author of the very successful 'Java Concurrency in Practice', and has published over 75 articles on software development.  He was the specification lead for JSR-335 (Lambda Expressions for the Java Language) and has served on numerous other JCP Expert Groups. 3
  • 4. Important disclaimers  THE INFORMATION CONTAINED IN THIS PRESENTATION IS PROVIDED FOR INFORMATIONAL PURPOSES ONLY.  WHILST EFFORTS WERE MADE TO VERIFY THE COMPLETENESS AND ACCURACY OF THE INFORMATION CONTAINED IN THIS PRESENTATION, IT IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.  ALL PERFORMANCE DATA INCLUDED IN THIS PRESENTATION HAVE BEEN GATHERED IN A CONTROLLED ENVIRONMENT. YOUR OWN TEST RESULTS MAY VARY BASED ON HARDWARE, SOFTWARE OR INFRASTRUCTURE DIFFERENCES.  ALL DATA INCLUDED IN THIS PRESENTATION ARE MEANT TO BE USED ONLY AS A GUIDE.  IN ADDITION, THE INFORMATION CONTAINED IN THIS PRESENTATION IS BASED ON IBM’S CURRENT PRODUCT PLANS AND STRATEGY, WHICH ARE SUBJECT TO CHANGE BY IBM, WITHOUT NOTICE.  IBM AND ITS AFFILIATED COMPANIES SHALL NOT BE RESPONSIBLE FOR ANY DAMAGES ARISING OUT OF THE USE OF, OR OTHERWISE RELATED TO, THIS PRESENTATION OR ANY OTHER DOCUMENTATION.  NOTHING CONTAINED IN THIS PRESENTATION IS INTENDED TO, OR SHALL HAVE THE EFFECT OF: – CREATING ANY WARRANT OR REPRESENTATION FROM IBM, ITS AFFILIATED COMPANIES OR ITS OR THEIR SUPPLIERS AND/OR LICENSORS 4
  • 5. Danger: highly technical talk!  This talk assumes you’re familiar with: – JVM bytecode set – java.lang.invoke.MethodHandle and related classes – invokedynamic 5
  • 6. Full bleed images preferred Text over top of full bleed images would be in white or a color from the color palette that would offer good contrast. Also, colored text in Arial Bold would have greater impact.
  • 9. The JVM: a highly tuned performance machine https://commons.wikimedia.org/wiki/File:Fernando_Alonso_2010_Jerez_test_14.jpg9
  • 10. It’s fastest when you stay on the path JVM optimized and tuned for the Java language. As long as the language maps cleanly to Java’s semantics, good perf is likely 10
  • 11. JVM invoke instructions  Prior to Java 7, there were 4 bytecodes to invoke methods: – invokespecial: constructors, super calls, private methods – invokevirtual: receiver based selection of instance methods – invokestatic: static methods – invokeinterface: interface based selection of instance methods  The semantics are tightly defined by the JVM spec 11
  • 13. Ruby fib  Show Ruby fib and outline why it’s not the same as the Java version 13 def fib(x) if x < 2 return x end return fib(x-2) + fib(x-1) end
  • 14. Ruby fib  6 method sends for Ruby vs 2 for Java 14 def fib(x) if x < 2 return x end return fib(x-2) + fib(x-1) end
  • 15. JRuby: ~1.6 implementation 15 CachingCallSite DynamicMethod @JRubyMethod(name = "+") public IRubyObject op_plus(ThreadContext ctx, IRubyObject other) { if (other instanceof RubyFixnum) { return addFixnum(ctx, (RubyFixnum)other); } return addOther(ctx, other); }
  • 16. Second class performance citizen: Dynamic languages  Simulation overheads: – Inlining depth limits – Inlining bytecode size limits – Reflection overhead – Non-inlinable caching / Hashtable lookups – Type mismatches: sharp types vs IRubyObject  Complexity – Generating invokers at build time based on annotations – Need to ensure the cache is correct 16
  • 18. Birth of JSR 292 EG 18 New JVM instruction, invokedynamic, designed to support the implementation of dynamically typed object oriented languages. … investigate support for hotswapping
  • 19. The problem: linkage + typing  JVM invoke instructions are tightly tied to Java – Linkage must match the JVM rules  My language uses different dispatch rules – Metaclass – Multiple dispatch – Mixins  User’s need to control the linkage 19 https://en.wikipedia.org/wiki/Burr_puzzle#/media/File:SixPartWoodKnot.jpg
  • 20. RestartMethodException & VM method cache  Invokedynamic – like invokevirtual except:  arguments not required to match the method’s signature  support for “doesNotUnderstand” handler – recursive lookup for method exactly matching descriptor  else call handler, which can:  implement the method & return result  pick a method and return it (via RestartMethodException) > VM can cache the “restart” method 20
  • 21. From InvokeDynamic to target method Invokedynamic Target method 21 User supplied logic  Tell the VM what method to link to
  • 22. From InvokeDynamic to target method Invokedynamic Static data: Caller Method name Descriptor Other data Target method 22 User supplied logic  Tell the VM what method to link to BootstrapMethod
  • 23. From InvokeDynamic to target method Invokedynamic java.lang.invoke.CallSite Target method 23 User supplied logic  Tell the VM what method to link to BootstrapMethod
  • 24. From InvokeDynamic to target method Invokedynamic java.lang.invoke.CallSite Target method 24 User supplied logic  Tell the VM what method to link to BootstrapMethod
  • 25. From InvokeDynamic to target method Invokedynamic Target method 25 java.lang.invoke.CallSite Indy is permanently linked to the CallSite (1 time) Invocation of target method can occur many times
  • 26. Anatomy of a CallSite 26 CallSite type target MethodType (String)V MethodHandle link(String)V
  • 27. Anatomy of a CallSite 27 CallSite type target MethodType (String)V MethodHandle link(String)V The link() handle does two things: 1. It sets CallSite target 2. Completes the call
  • 28. Anatomy of a CallSite 28 CallSite type target MethodType (String)V MethodHandle link(String)V GuardWithTest test target fallback MethodHandle Guard()boolean MethodHandle Method(String)V
  • 29. Invokedynamic: bytecode factory  Lazy constants  New semantics  New bytecodes  All these and more can be emulated using invokedynamic – Bootstrap Method to link the CallSite – Java code that implements the new operation – Really the ultimate bytecode emulation tool 29
  • 30. Interface injection A Class implements all the methods for an interface Doesn’t declare it implements it – How can we allow the interface invocation to proceed? 30 Foo foo = new Foo(); if (foo instanceof Injected) { Injected i = (Injected) foo; System.out.println(i.m()); } instanceof checkcast invokeinterface
  • 31. Interface injection: 3 Bootstrap Methods 31
  • 33. Interface injection: bytecode 33 0: new #14 // class Foo 3: dup 4: invokespecial #15 // Method Foo."<init>":()V 7: astore_1 8: aload_1 9: invokedynamic #28, 0 // InvokeDynamic #0:instanceof:(LObject;)Z 14: ifeq 36 17: aload_1 18: invokedynamic #36, 0 // InvokeDynamic #1:checkcast:(LObject;)LInjected; 23: astore_2 24: getstatic #42 // Field System.out:LPrintStream; 27: aload_2 28: invokedynamic #50, 0 // InvokeDynamic #2:m:(LObject;)LString; 33: invokevirtual #56 // Method PrintStream.println:(LString;)V 36: return BootstrapMethods: 0: #22 invokestatic Runtime.instanceOfBSM:(LLookup;LString;LMethodType;LClass;)LCallSite; Method arguments: #24 Injected 1: #32 invokestatic Runtime.checkcastBSM:(LLookup;LString;LMethodType;LClass;)LCallSite; Method arguments: #24 Injected 2: #46 invokestatic Runtime.invokeinterfaceBSM:(LLookup;LString;LMethodType;Ljava/lang/Class;)LCallSite; Method arguments: #24 Injected
  • 34. [jsr-292-eg] our package name 01/06/2011  Invokedynamic is more than dynamic languages!  Lambda can be built on top of invokedynamic and MethodHandles  (Painfully) renamed the package from java.dyn to java.lang.invoke at development cutoff 34
  • 35. Birth of JSR 292 EG 35 New JVM instruction, invokedynamic, designed to support the implementation of dynamically typed object oriented languages. … investigate support for hotswapping
  • 36. Wait, what is a dyn language anyway? Static Dynamic 36
  • 37. Wait, what is a dyn language anyway? Static Dynamic 37 Compile time Runtime
  • 38. Wait, what is a dyn language anyway? Static Dynamic 38 Compile time Runtime
  • 39. Wait, what is a dyn language anyway? Static Typing Dispatch Dynamic Binding (Un)Loading 39
  • 40. Its not just for dynamic languages anymore  Java 8 gave us Lambda expressions – But how do we compile this lambda? 40 Predicate<Person> pred = p -> p.age < minAge;
  • 41. Its not just for dynamic languages anymore  So, if indy is for dynamic languages, why is the Java compiler using it? – All the types involved are static – We can use indy to give us a dynamic code generation strategy  Generate inner classes?  Use method handles?  Use dynamic proxies?  Use VM-private APIs for constructing objects?  Indy lets us turn this choice into a pure implementation detail – Separate from the binary representation 41
  • 42. Desugaring lambdas to methods  First, we desugar the lambda to a method – Signature matches functional interface method – Plus captured arguments prepended – Simplest lambdas desugar to static methods  But some need access to receiver, and so are instance methods 42 Predicate<Person> pred = p -> p.age < minAge; private static boolean lambda$1(int minAge, Person p) { return p.age < minAge; }
  • 43. Its not just for dynamic languages anymore  We use indy to embed a recipe for constructing a lambda, including – The desugared implementation method (static) – The functional interface we are converting to (static) – Additional metadata, such as serialization information (static) – Values captured from the lexical scope (dynamic)  The capture site is called the lambda factory – Invoked with indy, returns an instance of the desired functional interface – Subsequent captures bypass the (slow) linkage path 43
  • 44. Factories and metafactories  We generate an indy call site which, when called, returns the lambda – This is the lambda factory – Bootstrap for the lambda factory selects the translation strategy  Bootstrap is called the lambda metafactory  Part of Java runtime – Captured args passed to lambda factory 44 list.removeIf(p -> p.age < minAge); private static boolean lambda$1(int minAge, Person p) { return p.getAge() >= minAge; } Predicate $p = indy[bootstrap=LambdaMetafactory, staticargs=[Predicate, lambda$1], dynargs=[minAge]) list.removeIf($p);
  • 45. Full bleed images preferred Text over top of full bleed images would be in white or a color from the color palette that would offer good contrast. Also, colored text in Arial Bold would have greater impact.
  • 46. Optimized String concat (JEP tbd) 46 String m(String a, int b) { return a + "(" + b + ")"; } java.lang.String m(java.lang.String, int); 0: new #2 // class StringBuilder 3: dup 4: invokespecial #3 // Method StringBuilder.<init>:()V 7: aload_1 8: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder; 11: ldc #5 // String ( 13: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder; 16: iload_2 17: invokevirtual #6 // Method StringBuilder.append:(I)LStringBuilder; 20: ldc #7 // String ) 22: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder; 25: invokevirtual #8 // Method StringBuilder.toString:()LString; 28: areturn http://openjdk.java.net/jeps/8085796
  • 47. Optimized String concat (JEP tbd) 47 String m(String a, int b) { return a + "(" + b + ")"; } java.lang.String m(java.lang.String, int); 0: aload_1 1: ldc #2 // String ( 3: iload_2 4: ldc #3 // String ) 6: invokedynamic #4, 0 // InvokeDynamic #0:stringConcat:(LString;LString;ILString;)LString; 11: areturn BootstrapMethods: 0: #19 invokestatic StringConcatFactory.stringConcat: (LMethodHandles$Lookup;LString;LMethodType;LString;[LObject;)LCallSite; http://openjdk.java.net/jeps/8085796
  • 48. 48
  • 49. Invoking Specialized Generic Static Methods  We need to capture the type argument at the callsite.  How does m access the type information at run-time? class C { static <any T> T m(T i) {…} } int i = C.<int>m(3);
  • 50.  Embed specialized type information in the invokedynamic Callsite Invoking Specialized Static Methods (cont’d) 7: iconst_3 8: invokedynamic #4, 0 // InvokeDynamic #0:m:(LFoo;I)V BootstrapMethods: 0: #26 invokestatic GenericMethodSpecializer.metafactory: (LMethodHandles$Lookup;LString;LMethodType;[LObject;)LCallSite; Method arguments: #27 LC; #28 invokevirtual C.m:(LObject;)V #29 I
  • 51. 51
  • 52. 52 Legal Notice IBM and the IBM logo are trademarks or registered trademarks of IBM Corporation, in the United States, other countries or both. Java and all Java-based marks, among others, are trademarks or registered trademarks of Oracle in the United States, other countries or both. Other company, product and service names may be trademarks or service marks of others. THE INFORMATION DISCUSSED IN THIS PRESENTATION IS PROVIDED FOR INFORMATIONAL PURPOSES ONLY. WHILE EFFORTS WERE MADE TO VERIFY THE COMPLETENESS AND ACCURACY OF THE INFORMATION, IT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, AND IBM SHALL NOT BE RESPONSIBLE FOR ANY DAMAGES ARISING OUT OF THE USE OF, OR OTHERWISE RELATED TO, SUCH INFORMATION. ANY INFORMATION CONCERNING IBM'S PRODUCT PLANS OR STRATEGY IS SUBJECT TO CHANGE BY IBM WITHOUT NOTICE.