SlideShare a Scribd company logo
How the HotSpot and Graal JVMs
Execute Java Code
James Gough - @Jim__Gough
• University of Warwick Graduate
• Interested in compilers and performance
• London Java Community
• Helped design and test JSR-310 (Date Time)
• Developer and Trainer
• Teaching Java and C++ to graduates
• Co-Author of Optimizing Java
• Developer on Java based API Gateways
• Occasional Maven Hacker
About Me
@Jim__Gough
Exploring the JVM
@Jim__Gough
JIT Compiler
Emitter
Method Cache
JVM
Interpreter
classloader
Java
source
code
.class
file
javac
Profile Data
Code Cache
Building Java Applications
@Jim__Gough
JIT Compiler
Emitter
Method Cache
JVM
Interpreter
classloader
Java
source
code
.class
file
javac
Profile Data
Code Cache
A Simple Example
@Jim__Gough
public class HelloWorld {
public static void main(String[] args) {
for(int i=0; i < 1_000_000; i++) {
printInt(i);
}
}
public static void printInt(int number) {
System.err.println("Hello World" + number);
}
}
.class
filejavac javap
public HelloWorld();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: ldc #2 // int 1000000
5: if_icmpge 18
8: iload_1
9: invokestatic #3 // Method printInt:(I)V
12: iinc 1, 1
15: goto 2
18: return
A Simple Example
@Jim__Gough
public static void printInt(int);
Code:
0: getstatic #4
// Field java/lang/System.err:Ljava/io/PrintStream;
3: iload_0
4: invokedynamic #5, 0
// InvokeDynamic #0:makeConcatWithConstants:(I)Ljava/lang/String;
9: invokevirtual #6
// Method java/io/PrintStream.println:(Ljava/lang/String;)V
12: return
public static void printInt(int);
Code:
0: getstatic #4 // Field java/lang/System.err:Ljava/io/PrintStream;
3: new #5 // class java/lang/StringBuilder
6: dup
7: invokespecial #6 // Method java/lang/StringBuilder."<init>":()V
10: ldc #7 // String Hello World
12: invokevirtual #8
// Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
Java 8 Java 9+
Classloaders
@Jim__Gough
JIT Compiler
Emitter
Method Cache
JVM
Interpreter
classloader
Java
source
code
.class
file
javac
Profile Data
Code Cache
Classloaders
• Classes are loaded just before they are needed
• Proven by the painful ClassNotFoundException, NoClassDefFoundError
• Build tools hide this problem away from us
• Maps class file contents into the JVM klass object
• Instance Methods are held in the klassVtable
• Static variables are held in the instanceKlass
• You can write your own classloader to experiment
• https://github.com/jpgough/watching-classloader
@Jim__Gough
Interpreting Bytecode
@Jim__Gough
JIT Compiler
Emitter
Method Cache
JVM
classloader
Java
source
code
.class
file
javac
Profile Data
Code Cache
Interpreter
Interpreting Bytecode
• Bytecode initially fully interpreted
• Conversion of instructions to machine instructions
• Using template interpreter
• Time not spent compiling code that is only used once
• Allows the JVM to establish “true profile” of the application
@Jim__Gough
https://speakerdeck.com/alblue/javaone-2016-hotspot-under-the-hood?slide=21
Just in Time Compilation (JIT)
@Jim__Gough
JIT Compiler
Emitter
Method Cache
JVM
classloader
Java
source
code
.class
file
javac
Profile Data
Code Cache
Interpreter
The HotSpot Compiler
@Jim__Gough
• Java observes code executing using profile data
• Triggers a compilation request on meeting the threshold
• Startup methods may only be invoked a few times
• Utilising the profile enables informed optimisation
• Classloaders mean then JVM doesn’t know what will run
• Emits machine code to replace interpreted bytecode
• C2 is the main HotSpot Compiler implemented in C++
Challenges with the C2 Compiler
@Jim__Gough
C++
Unsafe Legacy
Ordinary Object
Pointer (OOP)
Custom Malloc is
pointless
Difficult to make
changes
Tooling
Built upon over 20 years
Awesome Engineering
Java is now fast enough
to be a compiler?
Evolving the JIT Compiler
@Jim__Gough
JIT Compiler
Method Cache
JVM
classloader
Java
source
code
.class
file
javac
EmitterProfiler
Code Cache
Interpreter JVM Compiler Interface
JVM Compiler Interface (JVMCI)
@Jim__Gough
• Provides access to VM structures for compiler
• Fields, methods, profile information…
• Mechanism to install the compiled code
• Along with metadata required for GC and deoptimization
• Produce machine code at a method level
• Uses JEP-261 (Modules) to protect and isolate
Graal as a JIT
@Jim__Gough
• A JIT compiler has a simple series of inputs
• Method to compile to convert bytecode to assembly
• A graph of nodes to convey the structure and context
• The profile of the running application
• Implementing a JIT in Java is quite compelling
• Language level safety in expressions
• Easy to debug, great tools and IDE support
Getting Started with Graal
@Jim__Gough
• mx command line tool for graal
• pull in the graalvm project (work within graal/compiler)
• mx build to build our local compiler mx ideinit
• mx -d vm (debug and install our local suite as the vm)
-XX:+UnlockExperimentalVMOptions
-XX:+EnableJVMCI
-XX:+UseJVMCICompiler
-XX:-TieredCompilation
-XX:CompileOnly=HelloWorld,System/err/println
-Dgraal.Dump
HelloWorld
Getting Started with Graal
@Jim__Gough
• IdealGraphVisualizer - Oracle Enterprise tool
Exploring Inlining
@Jim__Gough
main()
printInt
println
Frame Pointer
Return Address
Locals
Parameters
Return Address
Locals
Parameters
Return Address
Locals
Parameters
Live Debug
@Jim__Gough
Compilation Tiers and Phases
@Jim__Gough
1. CanonicalizerPhase

2. InliningPhase
3. DeadCodeEliminationPhase
4. IncrementalCanonicalizerPhase 

5. IterativeConditionalEliminationPhase

6. LoopFullUnrollPhase
7. IncrementalCanonicalizerPhase 

8. IncrementalCanonicalizerPhase 

9. PartialEscapePhase
10. EarlyReadEliminationPhase

11. LoweringPhase
1. LockEliminationPhase

2. IncrementalCanonicalizerPhase 

3. IterativeConditionalEliminationPhase

4. LoopSafepointEliminationPhase

5. GuardLoweringPhase

6. IncrementalCanonicalizerPhase 

7. LoopSafepointInsertionPhase

8. LoweringPhase

9. OptimizeDivPhase

10. FrameStateAssignmentPhase 

11. LoopPartialUnrollPhase

12. ReassociateInvariantPhase

13. DeoptimizationGroupingPhase 

14. CanonicalizerPhase

15. WriteBarrierAdditionPhase
1. LoweringPhase

2. ExpandLogicPhase

3. FixReadsPhase

4. CanonicalizerPhase

5. AddressLoweringPhase

6. UseTrappingNullChecksPhase

7. DeadCodeEliminationPhase
8. PropagateDeoptimizeProbabilityPhase

9. InsertMembarsPhase

10. SchedulePhase
High Tier Mid Tier Low Tier
Dead Code Elimination
• Removes code that is never executed
• Shrinks the size of the program
• Avoids executing irrelevant operations
• Dynamic dead code elimination
• Eliminated base on possible set of values
• Determined at runtime
@Jim__Gough
• Iteration requires back branches and branch prediction
• For int, char and short loops loop can be unrolled
• Can remove safe point checks
• Reduces the work needed by each “iteration”
Loop Unrolling
@Jim__Gough
Loop Unrolling
@Benchmark
public long intStride() {
long sum = 0;
for (int i = 0; i < MAX; i++) {
sum += data[i];
}
return sum;
}
Benchmark Mode Cnt Score Error Units
LoopUnrollingCounter.intStride thrpt 200 2423.818 ± 2.547 ops/s
LoopUnrollingCounter.longStride thrpt 200 1469.833 ± 0.721 ops/s
@Jim__Gough
@Benchmark
public long longStride() {
long sum = 0;
for (long l = 0; l < MAX; l++) {
sum += data[(int) l];
}
return sum;
}
Excerpt From: Benjamin J. Evans, James Gough, and Chris Newland. “Optimizing Java.”.
• Introduced in later versions of Java 6
• Analyses code to assert if an object
• Returns or leaves the scope of the method
• Stored in global variables
• Allocates unescaped objects on the stack
• Avoids the cost of garbage collection
• Prevents workload pressures on Eden
• Beneficial effects to counter high infant mortality GC impact
Escape Analysis
@Jim__Gough
• When HotSpot encounters a virtual call site, often only
one type will ever be seen there
• e.g. There's only one implementing class for an interface
• Hotspot can optimise vtable lookup
• Subclasses have the same vtable structure as their parent
• Hotspot can collapse the child into the parent
• Classloading tricks can invalidate monomorphic dispatch
• The class word in the header is checked
• If changed then this optimisation is backed out
Monomorphic Dispatch
@Jim__Gough
Code Cache
@Jim__Gough
JIT Compiler
Emitter
Method Cache
JVM
classloader
Java
source
code
.class
file
javac
Profile Data
Code Cache
Interpreter
AOT
Ahead of Time Compilation
@Jim__Gough
• Achieved using a new tool called jaotc
• Graal is used as the code generating backend
• JVM treats AOT code as an extension to the code cache
• JVM must reject incompatible code
• Fingerprinting techniques are used
• jaotc --output libHelloWorld.so HelloWorld.class
• java -XX:+UnlockExperimentalVMOptions
-XX:AOTLibrary=./libHelloWorld.so HelloWorld
The Bigger Picture
@Jim__Gough
Java
source
code
.class
file
javac
Garbage
Collection
Databases/Networks/IO bound operations
JIT Compiler
Emitter
Method Cache
JVM
classloader
Profile Data
Code Cache
Interpreter
Acknowledgements
@Jim__Gough
• Chris Seaton for his excellent initial post on Graal as a JIT
• Ben Evans for his education, patience and friendship
• Anna Evans for some of the amazing slide graphics
• Martijn Verburg for encouragement and support
• GraalVM and OpenJDK team for the projects
• Alex Blewitt for talk review and HotSpot Under the Hood talk
• NY Java SIG for hosting trial run
Thanks for Listening
James Gough - @Jim__Gough

More Related Content

What's hot

Ruby3x3: How are we going to measure 3x
Ruby3x3: How are we going to measure 3xRuby3x3: How are we going to measure 3x
Ruby3x3: How are we going to measure 3xMatthew Gaudet
 
Jvm tuning in a rush! - Lviv JUG
Jvm tuning in a rush! - Lviv JUGJvm tuning in a rush! - Lviv JUG
Jvm tuning in a rush! - Lviv JUGTomek Borek
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesCharles Nutter
 
Large-scaled Deploy Over 100 Servers in 3 Minutes
Large-scaled Deploy Over 100 Servers in 3 MinutesLarge-scaled Deploy Over 100 Servers in 3 Minutes
Large-scaled Deploy Over 100 Servers in 3 MinutesHiroshi SHIBATA
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaKeith Bennett
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzIvan Krylov
 
Middleware as Code with mruby
Middleware as Code with mrubyMiddleware as Code with mruby
Middleware as Code with mrubyHiroshi SHIBATA
 
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia "What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia Vladimir Ivanov
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript ProgrammingYoshiki Shibukawa
 
Graal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them AllGraal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them AllThomas Wuerthinger
 
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)ngotogenome
 
JVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovJVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovZeroTurnaround
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9Ivan Krylov
 
Experiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyExperiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyMatthew Gaudet
 
Launchpad: Lessons Learnt
Launchpad: Lessons LearntLaunchpad: Lessons Learnt
Launchpad: Lessons LearntTim Penhey
 
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"Fwdays
 
Burp Plugin Development for Java n00bs - 44CON 2012
Burp Plugin Development for Java n00bs - 44CON 2012Burp Plugin Development for Java n00bs - 44CON 2012
Burp Plugin Development for Java n00bs - 44CON 201244CON
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineChun-Yu Wang
 

What's hot (20)

Ruby3x3: How are we going to measure 3x
Ruby3x3: How are we going to measure 3xRuby3x3: How are we going to measure 3x
Ruby3x3: How are we going to measure 3x
 
Jvm tuning in a rush! - Lviv JUG
Jvm tuning in a rush! - Lviv JUGJvm tuning in a rush! - Lviv JUG
Jvm tuning in a rush! - Lviv JUG
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for Dummies
 
Large-scaled Deploy Over 100 Servers in 3 Minutes
Large-scaled Deploy Over 100 Servers in 3 MinutesLarge-scaled Deploy Over 100 Servers in 3 Minutes
Large-scaled Deploy Over 100 Servers in 3 Minutes
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-java
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
 
Middleware as Code with mruby
Middleware as Code with mrubyMiddleware as Code with mruby
Middleware as Code with mruby
 
Groovy & Grails
Groovy & GrailsGroovy & Grails
Groovy & Grails
 
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia "What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript Programming
 
Graal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them AllGraal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them All
 
How DSL works on Ruby
How DSL works on RubyHow DSL works on Ruby
How DSL works on Ruby
 
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
 
JVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovJVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir Ivanov
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
 
Experiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyExperiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRuby
 
Launchpad: Lessons Learnt
Launchpad: Lessons LearntLaunchpad: Lessons Learnt
Launchpad: Lessons Learnt
 
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
 
Burp Plugin Development for Java n00bs - 44CON 2012
Burp Plugin Development for Java n00bs - 44CON 2012Burp Plugin Development for Java n00bs - 44CON 2012
Burp Plugin Development for Java n00bs - 44CON 2012
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
 

Similar to How the HotSpot and Graal JVMs execute Java Code

GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22Jorge Hidalgo
 
Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native CompilerSimon Ritter
 
GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18Jorge Hidalgo
 
Gr8conf EU 2013 Speed up your development: GroovyServ and Grails Improx Plugin
Gr8conf EU 2013 Speed up your development: GroovyServ and Grails Improx PluginGr8conf EU 2013 Speed up your development: GroovyServ and Grails Improx Plugin
Gr8conf EU 2013 Speed up your development: GroovyServ and Grails Improx PluginYasuharu Nakano
 
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5David Voyles
 
Simple tweaks to get the most out of your jvm
Simple tweaks to get the most out of your jvmSimple tweaks to get the most out of your jvm
Simple tweaks to get the most out of your jvmJamie Coleman
 
Micronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless EraMicronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless Eragraemerocher
 
Groovy In the Cloud
Groovy In the CloudGroovy In the Cloud
Groovy In the CloudJim Driscoll
 
Simple tweaks to get the most out of your JVM
Simple tweaks to get the most out of your JVMSimple tweaks to get the most out of your JVM
Simple tweaks to get the most out of your JVMJamie Coleman
 
JavaScript Engine and WebAssembly
JavaScript Engine and WebAssemblyJavaScript Engine and WebAssembly
JavaScript Engine and WebAssemblyChanghwan Yi
 
FOSDEM 2017 - Open J9 The Next Free Java VM
FOSDEM 2017 - Open J9 The Next Free Java VMFOSDEM 2017 - Open J9 The Next Free Java VM
FOSDEM 2017 - Open J9 The Next Free Java VMCharlie Gracie
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceESUG
 
White and Black Magic on the JVM
White and Black Magic on the JVMWhite and Black Magic on the JVM
White and Black Magic on the JVMIvaylo Pashov
 
The Performance Engineer's Guide To HotSpot Just-in-Time Compilation
The Performance Engineer's Guide To HotSpot Just-in-Time CompilationThe Performance Engineer's Guide To HotSpot Just-in-Time Compilation
The Performance Engineer's Guide To HotSpot Just-in-Time CompilationMonica Beckwith
 
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
 
Polygot Java EE on the GraalVM
Polygot Java EE on the GraalVMPolygot Java EE on the GraalVM
Polygot Java EE on the GraalVMRyan Cuprak
 
Head first android apps dev tools
Head first android apps dev toolsHead first android apps dev tools
Head first android apps dev toolsShaka Huang
 
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
 
Hacking Java @JavaLand2016
Hacking Java @JavaLand2016Hacking Java @JavaLand2016
Hacking Java @JavaLand2016Sean P. Floyd
 

Similar to How the HotSpot and Graal JVMs execute Java Code (20)

GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22
 
Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native Compiler
 
GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18
 
Gr8conf EU 2013 Speed up your development: GroovyServ and Grails Improx Plugin
Gr8conf EU 2013 Speed up your development: GroovyServ and Grails Improx PluginGr8conf EU 2013 Speed up your development: GroovyServ and Grails Improx Plugin
Gr8conf EU 2013 Speed up your development: GroovyServ and Grails Improx Plugin
 
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
 
Simple tweaks to get the most out of your jvm
Simple tweaks to get the most out of your jvmSimple tweaks to get the most out of your jvm
Simple tweaks to get the most out of your jvm
 
Micronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless EraMicronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless Era
 
Groovy In the Cloud
Groovy In the CloudGroovy In the Cloud
Groovy In the Cloud
 
Java for the Beginners
Java for the BeginnersJava for the Beginners
Java for the Beginners
 
Simple tweaks to get the most out of your JVM
Simple tweaks to get the most out of your JVMSimple tweaks to get the most out of your JVM
Simple tweaks to get the most out of your JVM
 
JavaScript Engine and WebAssembly
JavaScript Engine and WebAssemblyJavaScript Engine and WebAssembly
JavaScript Engine and WebAssembly
 
FOSDEM 2017 - Open J9 The Next Free Java VM
FOSDEM 2017 - Open J9 The Next Free Java VMFOSDEM 2017 - Open J9 The Next Free Java VM
FOSDEM 2017 - Open J9 The Next Free Java VM
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performance
 
White and Black Magic on the JVM
White and Black Magic on the JVMWhite and Black Magic on the JVM
White and Black Magic on the JVM
 
The Performance Engineer's Guide To HotSpot Just-in-Time Compilation
The Performance Engineer's Guide To HotSpot Just-in-Time CompilationThe Performance Engineer's Guide To HotSpot Just-in-Time Compilation
The Performance Engineer's Guide To HotSpot Just-in-Time Compilation
 
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
 
Polygot Java EE on the GraalVM
Polygot Java EE on the GraalVMPolygot Java EE on the GraalVM
Polygot Java EE on the GraalVM
 
Head first android apps dev tools
Head first android apps dev toolsHead first android apps dev tools
Head first android apps dev tools
 
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
 
Hacking Java @JavaLand2016
Hacking Java @JavaLand2016Hacking Java @JavaLand2016
Hacking Java @JavaLand2016
 

Recently uploaded

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsVlad Stirbu
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...Elena Simperl
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...Sri Ambati
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform EngineeringJemma Hussein Allen
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backElena Simperl
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
 

Recently uploaded (20)

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 

How the HotSpot and Graal JVMs execute Java Code

  • 1. How the HotSpot and Graal JVMs Execute Java Code James Gough - @Jim__Gough
  • 2. • University of Warwick Graduate • Interested in compilers and performance • London Java Community • Helped design and test JSR-310 (Date Time) • Developer and Trainer • Teaching Java and C++ to graduates • Co-Author of Optimizing Java • Developer on Java based API Gateways • Occasional Maven Hacker About Me @Jim__Gough
  • 3. Exploring the JVM @Jim__Gough JIT Compiler Emitter Method Cache JVM Interpreter classloader Java source code .class file javac Profile Data Code Cache
  • 4. Building Java Applications @Jim__Gough JIT Compiler Emitter Method Cache JVM Interpreter classloader Java source code .class file javac Profile Data Code Cache
  • 5. A Simple Example @Jim__Gough public class HelloWorld { public static void main(String[] args) { for(int i=0; i < 1_000_000; i++) { printInt(i); } } public static void printInt(int number) { System.err.println("Hello World" + number); } } .class filejavac javap public HelloWorld(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: iconst_0 1: istore_1 2: iload_1 3: ldc #2 // int 1000000 5: if_icmpge 18 8: iload_1 9: invokestatic #3 // Method printInt:(I)V 12: iinc 1, 1 15: goto 2 18: return
  • 6. A Simple Example @Jim__Gough public static void printInt(int); Code: 0: getstatic #4 // Field java/lang/System.err:Ljava/io/PrintStream; 3: iload_0 4: invokedynamic #5, 0 // InvokeDynamic #0:makeConcatWithConstants:(I)Ljava/lang/String; 9: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 12: return public static void printInt(int); Code: 0: getstatic #4 // Field java/lang/System.err:Ljava/io/PrintStream; 3: new #5 // class java/lang/StringBuilder 6: dup 7: invokespecial #6 // Method java/lang/StringBuilder."<init>":()V 10: ldc #7 // String Hello World 12: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; Java 8 Java 9+
  • 8. Classloaders • Classes are loaded just before they are needed • Proven by the painful ClassNotFoundException, NoClassDefFoundError • Build tools hide this problem away from us • Maps class file contents into the JVM klass object • Instance Methods are held in the klassVtable • Static variables are held in the instanceKlass • You can write your own classloader to experiment • https://github.com/jpgough/watching-classloader @Jim__Gough
  • 9. Interpreting Bytecode @Jim__Gough JIT Compiler Emitter Method Cache JVM classloader Java source code .class file javac Profile Data Code Cache Interpreter
  • 10. Interpreting Bytecode • Bytecode initially fully interpreted • Conversion of instructions to machine instructions • Using template interpreter • Time not spent compiling code that is only used once • Allows the JVM to establish “true profile” of the application @Jim__Gough https://speakerdeck.com/alblue/javaone-2016-hotspot-under-the-hood?slide=21
  • 11. Just in Time Compilation (JIT) @Jim__Gough JIT Compiler Emitter Method Cache JVM classloader Java source code .class file javac Profile Data Code Cache Interpreter
  • 12. The HotSpot Compiler @Jim__Gough • Java observes code executing using profile data • Triggers a compilation request on meeting the threshold • Startup methods may only be invoked a few times • Utilising the profile enables informed optimisation • Classloaders mean then JVM doesn’t know what will run • Emits machine code to replace interpreted bytecode • C2 is the main HotSpot Compiler implemented in C++
  • 13. Challenges with the C2 Compiler @Jim__Gough C++ Unsafe Legacy Ordinary Object Pointer (OOP) Custom Malloc is pointless Difficult to make changes Tooling Built upon over 20 years Awesome Engineering Java is now fast enough to be a compiler?
  • 14. Evolving the JIT Compiler @Jim__Gough JIT Compiler Method Cache JVM classloader Java source code .class file javac EmitterProfiler Code Cache Interpreter JVM Compiler Interface
  • 15. JVM Compiler Interface (JVMCI) @Jim__Gough • Provides access to VM structures for compiler • Fields, methods, profile information… • Mechanism to install the compiled code • Along with metadata required for GC and deoptimization • Produce machine code at a method level • Uses JEP-261 (Modules) to protect and isolate
  • 16. Graal as a JIT @Jim__Gough • A JIT compiler has a simple series of inputs • Method to compile to convert bytecode to assembly • A graph of nodes to convey the structure and context • The profile of the running application • Implementing a JIT in Java is quite compelling • Language level safety in expressions • Easy to debug, great tools and IDE support
  • 17. Getting Started with Graal @Jim__Gough • mx command line tool for graal • pull in the graalvm project (work within graal/compiler) • mx build to build our local compiler mx ideinit • mx -d vm (debug and install our local suite as the vm) -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI -XX:+UseJVMCICompiler -XX:-TieredCompilation -XX:CompileOnly=HelloWorld,System/err/println -Dgraal.Dump HelloWorld
  • 18. Getting Started with Graal @Jim__Gough • IdealGraphVisualizer - Oracle Enterprise tool
  • 19. Exploring Inlining @Jim__Gough main() printInt println Frame Pointer Return Address Locals Parameters Return Address Locals Parameters Return Address Locals Parameters
  • 21. Compilation Tiers and Phases @Jim__Gough 1. CanonicalizerPhase 2. InliningPhase 3. DeadCodeEliminationPhase 4. IncrementalCanonicalizerPhase 5. IterativeConditionalEliminationPhase 6. LoopFullUnrollPhase 7. IncrementalCanonicalizerPhase 8. IncrementalCanonicalizerPhase 9. PartialEscapePhase 10. EarlyReadEliminationPhase 11. LoweringPhase 1. LockEliminationPhase 2. IncrementalCanonicalizerPhase 3. IterativeConditionalEliminationPhase 4. LoopSafepointEliminationPhase 5. GuardLoweringPhase 6. IncrementalCanonicalizerPhase 7. LoopSafepointInsertionPhase 8. LoweringPhase 9. OptimizeDivPhase 10. FrameStateAssignmentPhase 11. LoopPartialUnrollPhase 12. ReassociateInvariantPhase 13. DeoptimizationGroupingPhase 14. CanonicalizerPhase 15. WriteBarrierAdditionPhase 1. LoweringPhase 2. ExpandLogicPhase 3. FixReadsPhase 4. CanonicalizerPhase 5. AddressLoweringPhase 6. UseTrappingNullChecksPhase 7. DeadCodeEliminationPhase 8. PropagateDeoptimizeProbabilityPhase 9. InsertMembarsPhase 10. SchedulePhase High Tier Mid Tier Low Tier
  • 22. Dead Code Elimination • Removes code that is never executed • Shrinks the size of the program • Avoids executing irrelevant operations • Dynamic dead code elimination • Eliminated base on possible set of values • Determined at runtime @Jim__Gough
  • 23. • Iteration requires back branches and branch prediction • For int, char and short loops loop can be unrolled • Can remove safe point checks • Reduces the work needed by each “iteration” Loop Unrolling @Jim__Gough
  • 24. Loop Unrolling @Benchmark public long intStride() { long sum = 0; for (int i = 0; i < MAX; i++) { sum += data[i]; } return sum; } Benchmark Mode Cnt Score Error Units LoopUnrollingCounter.intStride thrpt 200 2423.818 ± 2.547 ops/s LoopUnrollingCounter.longStride thrpt 200 1469.833 ± 0.721 ops/s @Jim__Gough @Benchmark public long longStride() { long sum = 0; for (long l = 0; l < MAX; l++) { sum += data[(int) l]; } return sum; } Excerpt From: Benjamin J. Evans, James Gough, and Chris Newland. “Optimizing Java.”.
  • 25. • Introduced in later versions of Java 6 • Analyses code to assert if an object • Returns or leaves the scope of the method • Stored in global variables • Allocates unescaped objects on the stack • Avoids the cost of garbage collection • Prevents workload pressures on Eden • Beneficial effects to counter high infant mortality GC impact Escape Analysis @Jim__Gough
  • 26. • When HotSpot encounters a virtual call site, often only one type will ever be seen there • e.g. There's only one implementing class for an interface • Hotspot can optimise vtable lookup • Subclasses have the same vtable structure as their parent • Hotspot can collapse the child into the parent • Classloading tricks can invalidate monomorphic dispatch • The class word in the header is checked • If changed then this optimisation is backed out Monomorphic Dispatch @Jim__Gough
  • 27. Code Cache @Jim__Gough JIT Compiler Emitter Method Cache JVM classloader Java source code .class file javac Profile Data Code Cache Interpreter AOT
  • 28. Ahead of Time Compilation @Jim__Gough • Achieved using a new tool called jaotc • Graal is used as the code generating backend • JVM treats AOT code as an extension to the code cache • JVM must reject incompatible code • Fingerprinting techniques are used • jaotc --output libHelloWorld.so HelloWorld.class • java -XX:+UnlockExperimentalVMOptions -XX:AOTLibrary=./libHelloWorld.so HelloWorld
  • 29. The Bigger Picture @Jim__Gough Java source code .class file javac Garbage Collection Databases/Networks/IO bound operations JIT Compiler Emitter Method Cache JVM classloader Profile Data Code Cache Interpreter
  • 30. Acknowledgements @Jim__Gough • Chris Seaton for his excellent initial post on Graal as a JIT • Ben Evans for his education, patience and friendship • Anna Evans for some of the amazing slide graphics • Martijn Verburg for encouragement and support • GraalVM and OpenJDK team for the projects • Alex Blewitt for talk review and HotSpot Under the Hood talk • NY Java SIG for hosting trial run
  • 31. Thanks for Listening James Gough - @Jim__Gough