SlideShare a Scribd company logo
White and Black
Magic on the
JVM
Ivaylo Pashov
Daniel Darakchiev
12 Nov 2018
Magic
on the JVM?
White
• Knowledge about Java language
and JVM specifications
• More efficient and optimized code
• Spells for troubleshooting
• Knowledge about the internal
implementation of the JVM
• Low level manipulation
• Subvert the JVM mechanics
• Great power  Great
responsibilities
Black
Compiler
Magic
Bytecode Compilation
• Platform independent and
language agnostic
• Compile-time constants inlining
• Tricks around type erasure, nested
classes and lambdas conversion
• Annotations processing
• Offloads from the developer the
need for code optimizations
• Unpredictable and inconsistent
• Limited set of configurations
JIT Compilation
Lambdas Translation vs Inner Class Translation
Definition
Compilation
public class LambdaSubmitter {
public void submit(ExecutorService executor) {
executor.submit(() ->
System.out.println("Called from " + this));
}
}
public class InnerClassSubmitter {
public void submit(ExecutorService executor) {
executor.submit(new Runnable() {
@Override
public void run() {
System.out.println("Called from " + this);
}
});
}
}
Lambdas Translation vs Inner Class Translation
Compilation
Linkage Classloading
ALOAD 0 //capturing this
INVOKEDYNAMIC run(LOuter;) LRunnable; [
LambdaMetafactory.metafactory(..)LCallSite;
()V, //Runnable argument types
Outer.lambda$submit$0()V,
()V // lambda$submit$0 argument types
]
//synthetic method containing lambda body
private synthetic lambda$submit$0()V
ALOAD 0 //capturing this
INVOKESPECIAL Outer$1.<init> (LOuter;)V
//class Outer$1
class Outer$1 implements Runnable {
final LOuter this$0;
<init>(LOuter;);
Lambdas Translation vs Inner Class Translation
Linkage Classloading
Capture Instantiate
Lambda
Metafactory
CallSite
create
Class
Loader
Outer$1
Class
load
Lambdas Translation vs Inner Class Translation
Capture Instantiate
Invoke
Runnable.run()
CallSite
Runnable
invoke with instance of
Outer
Outer$1 Class
Runnable
invoke with instance of
Outer
Lambdas and Method References Tips
• Avoid inner classes when possible
• No worse performance than inner classes in the worst case
• 5-20x better than inner classes in a common case
• Prefer non-capturing (stateless) lambdas/method references
• Faster capturing (reusing the call site)
• Easier to inline
• Prefer method references over lambdas
• Improved readability
• Avoid method generation
Combine the speed of compiled code with
the flexibility of interpretation
JIT (Just in Time) Compiler
Source (.java)
Bytecode (.class)
Native code
Optimizer
Run
Interpreter
Interperter vs JIT
• Simplest for of bytecode to
machine code translation
• Executes 1 bytecode
instruction at a time
• Repeated every time
bytecode is executed
• No opportunity to optimize
over an instruction set
• Easy to implement
• Fairly slow
• Look at entire or partial
context
• Optimization decisions based
on code graphs analysis
• Optimized native code stored
in code cache
• Runtime profiling – delayed
compilation
• Compiles hot methods only
as compilation is costly
JIT Impact on Performance
JIT compared to AOT
+ Advanced optimizations at runtime
+ Based on profiling
+ Optimized for target CPU
+ Global code optimizations
+ Better cache utilization
+ Only compile what is really needed (hot)
+ Reduces long build times
- Requires warmup period until reaching peak performance
- Increased CPU and memory usage
- Non-predictable execution overhead
- Optimistic – deoptimizing if wrong
JIT and Dynamic Dispatch
Classloading
Magic
Classloading Process
• Classloaders hierarchy
• Initialization order
• Laziness
• Classpath precedence
• Load a class multiple times
• Application servers
• Multi-versioned dependencies
• Insatiate a class via another class
• Define dynamic class at runtime
Custom Classloaders
Lazy Classloading
A class or interface typeT will be initialized immediately before the first
occurrence of any one of the following:
• Instance creation
• Static method invocation
• Static field read/write (except compile-time constants)
+Effective Metaspace (PermGen) management
– Can result in degraded performance after startup
Classloader Hierarchies
•Bootstrap CL loads the internal JVM classes
from the java.lang package
•The Extension CL (removed in Java 9) loads
everything from the java extension directory
•The System CL loads everything from the
classpath
•All user-defined CLs (usually) have the System
CL as their parent
Extension classloader
Bootstrap classloader
System classpath
classloader
…/lib/rt.jar
…/lib/ext/*.jar
$CLASSPATH
Memory Leaks
Class
Object
Classloader Class
Class
Class
Object
Object
Object
Static fields
All loaded classes
A single object
can leak its
classloader
Memory
Magic
Memory Access Patterns
• Memory access is crucial for
performance (locality)
• Tradeoff between encapsulation
and efficient memory layout
(objects vs. primitives)
• Method invocation cost
• Low level memory manipulation
(C-style memory access)
• Subverting Java memory
structures
• Heap vs off-heap (unmanaged)
Memory Manipulation
Stack vs Heap
final class Point {
final int x;
final int y;
}
Stack Heap
ref header
x
y
Allocated on
the Heap
More GC
Objects Layout
final class Point {
final int x;
final int y;
}
Point[] pts = header
header
x
y
header
x
y
header
x
y
Extra memory
for headers
Indirection
Objects Layout
int[] x = header int[] y = header
Objects Layout
Objects Layout
Instance Memory Representation
instance
0 mark
4 klass
8 field1
12 field2
…
class
0 vtbl ptr
4 layout_helper
8 super_check_offset
12 name
16 secondary_super_cache
20 secondary_supers
24 primary_supers 0
28 primary_supers 1
32 primary_supers 2
36 primary_supers 3
…
Memory Types
Heap vs Off-heap Memory
Heap
Off-heap
Stack
Managed by GC
Not Managed By
GC
Objects
Raw bytes
Serialization Benchmark
Agents
Magic
Java Agent
• Real Black Magic
• Bytecode manipulation technique
• Plugs into JVM and modifies classes loaded by the
class loader
• Extremely as powerful as dangerous
• Used with JDK up to Java 8, from Java 9 it is available in
the JRE
Launch Time
Instrumentation
Class
Loader
Class
Loader
Java Agent
1. premain()
Transformer
.class
files
2. register
3. load
5. bytes4. transform
JVM
MainClass
6. run main()
java –javaagent:/to/agent.jar MainClass
Other Process
JVM 1
Java Agent
agentmain()
JVM 2
VirtualMachine vm =
VirtualMachine.attach("2177");
vm.loadAgent(”/to/agent.jar",
”arg1=1");
pid=2177
Instrumentation
Same Process
JVM 1
Java Agent
agentmain()
Instrumentation

More Related Content

What's hot

Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
Surbhi Panhalkar
 
just in time JIT compiler
just in time JIT compilerjust in time JIT compiler
just in time JIT compiler
Mohit kumar
 
Java JVM
Java JVMJava JVM
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecture
subnesh
 
Java virtual machine
Java virtual machineJava virtual machine
3. jvm
3. jvm3. jvm
What's Inside a JVM?
What's Inside a JVM?What's Inside a JVM?
What's Inside a JVM?
Azul Systems Inc.
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
Nikhil Sharma
 
Architecture diagram of jvm
Architecture diagram of jvmArchitecture diagram of jvm
Architecture diagram of jvm
home
 
Jvm Architecture
Jvm ArchitectureJvm Architecture
Jvm Architecture
ThirupathiReddy Vajjala
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
Shashank L
 
Java Virtual Machine
Java Virtual Machine Java Virtual Machine
Java Virtual Machine
profbnk
 
Inside The Java Virtual Machine
Inside The Java Virtual MachineInside The Java Virtual Machine
Inside The Java Virtual Machine
elliando dias
 
Javantura v4 - JVM++ The GraalVM - Martin Toshev
Javantura v4 - JVM++ The GraalVM - Martin ToshevJavantura v4 - JVM++ The GraalVM - Martin Toshev
Javantura v4 - JVM++ The GraalVM - Martin Toshev
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
JAVA BYTE CODE
JAVA BYTE CODEJAVA BYTE CODE
JAVA BYTE CODE
Javed Ahmed Samo
 
Productionalizing Spark ML
Productionalizing Spark MLProductionalizing Spark ML
Productionalizing Spark ML
datamantra
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Scheidt & Bachmann
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
yoavwix
 
Neodev
NeodevNeodev

What's hot (20)

Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
 
just in time JIT compiler
just in time JIT compilerjust in time JIT compiler
just in time JIT compiler
 
Java JVM
Java JVMJava JVM
Java JVM
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecture
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
3. jvm
3. jvm3. jvm
3. jvm
 
What's Inside a JVM?
What's Inside a JVM?What's Inside a JVM?
What's Inside a JVM?
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Architecture diagram of jvm
Architecture diagram of jvmArchitecture diagram of jvm
Architecture diagram of jvm
 
Jvm Architecture
Jvm ArchitectureJvm Architecture
Jvm Architecture
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
Java Virtual Machine
Java Virtual Machine Java Virtual Machine
Java Virtual Machine
 
Inside The Java Virtual Machine
Inside The Java Virtual MachineInside The Java Virtual Machine
Inside The Java Virtual Machine
 
Javantura v4 - JVM++ The GraalVM - Martin Toshev
Javantura v4 - JVM++ The GraalVM - Martin ToshevJavantura v4 - JVM++ The GraalVM - Martin Toshev
Javantura v4 - JVM++ The GraalVM - Martin Toshev
 
JAVA BYTE CODE
JAVA BYTE CODEJAVA BYTE CODE
JAVA BYTE CODE
 
Productionalizing Spark ML
Productionalizing Spark MLProductionalizing Spark ML
Productionalizing Spark ML
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
 
Neodev
NeodevNeodev
Neodev
 

Similar to White and Black Magic on the JVM

A tour of Java and the JVM
A tour of Java and the JVMA tour of Java and the JVM
A tour of Java and the JVM
Alex Birch
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performance
ESUG
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
Vinay H G
 
02 cldc
02 cldc02 cldc
02 cldc
corneliuskoo
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
jyoti_lakhani
 
How the HotSpot and Graal JVMs execute Java Code
How the HotSpot and Graal JVMs execute Java CodeHow the HotSpot and Graal JVMs execute Java Code
How the HotSpot and Graal JVMs execute Java Code
Jim Gough
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in Java
Alex Moskvin
 
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
Vladimir Ivanov
 
Secrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on KubernetesSecrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on Kubernetes
Bruno Borges
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013
Vladimir Ivanov
 
Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native Compiler
Simon Ritter
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basics
tosine
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
Prashant Rane
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
Gal Marder
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
Victor Matyushevskyy
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
Omar Bashir
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
Mike Slinn
 
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
InfinIT - Innovationsnetværket for it
 
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Rhythm Suiwal
 

Similar to White and Black Magic on the JVM (20)

A tour of Java and the JVM
A tour of Java and the JVMA tour of Java and the JVM
A tour of Java and the JVM
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performance
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
02 cldc
02 cldc02 cldc
02 cldc
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
How the HotSpot and Graal JVMs execute Java Code
How the HotSpot and Graal JVMs execute Java CodeHow the HotSpot and Graal JVMs execute Java Code
How the HotSpot and Graal JVMs execute Java Code
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in Java
 
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
 
Secrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on KubernetesSecrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on Kubernetes
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013
 
Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native Compiler
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basics
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
 
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
 
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
 

Recently uploaded

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
Techgropse Pvt.Ltd.
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 

White and Black Magic on the JVM

  • 1. White and Black Magic on the JVM Ivaylo Pashov Daniel Darakchiev 12 Nov 2018
  • 3. White • Knowledge about Java language and JVM specifications • More efficient and optimized code • Spells for troubleshooting • Knowledge about the internal implementation of the JVM • Low level manipulation • Subvert the JVM mechanics • Great power  Great responsibilities Black
  • 5. Bytecode Compilation • Platform independent and language agnostic • Compile-time constants inlining • Tricks around type erasure, nested classes and lambdas conversion • Annotations processing • Offloads from the developer the need for code optimizations • Unpredictable and inconsistent • Limited set of configurations JIT Compilation
  • 6. Lambdas Translation vs Inner Class Translation Definition Compilation public class LambdaSubmitter { public void submit(ExecutorService executor) { executor.submit(() -> System.out.println("Called from " + this)); } } public class InnerClassSubmitter { public void submit(ExecutorService executor) { executor.submit(new Runnable() { @Override public void run() { System.out.println("Called from " + this); } }); } }
  • 7. Lambdas Translation vs Inner Class Translation Compilation Linkage Classloading ALOAD 0 //capturing this INVOKEDYNAMIC run(LOuter;) LRunnable; [ LambdaMetafactory.metafactory(..)LCallSite; ()V, //Runnable argument types Outer.lambda$submit$0()V, ()V // lambda$submit$0 argument types ] //synthetic method containing lambda body private synthetic lambda$submit$0()V ALOAD 0 //capturing this INVOKESPECIAL Outer$1.<init> (LOuter;)V //class Outer$1 class Outer$1 implements Runnable { final LOuter this$0; <init>(LOuter;);
  • 8. Lambdas Translation vs Inner Class Translation Linkage Classloading Capture Instantiate Lambda Metafactory CallSite create Class Loader Outer$1 Class load
  • 9. Lambdas Translation vs Inner Class Translation Capture Instantiate Invoke Runnable.run() CallSite Runnable invoke with instance of Outer Outer$1 Class Runnable invoke with instance of Outer
  • 10. Lambdas and Method References Tips • Avoid inner classes when possible • No worse performance than inner classes in the worst case • 5-20x better than inner classes in a common case • Prefer non-capturing (stateless) lambdas/method references • Faster capturing (reusing the call site) • Easier to inline • Prefer method references over lambdas • Improved readability • Avoid method generation
  • 11. Combine the speed of compiled code with the flexibility of interpretation JIT (Just in Time) Compiler Source (.java) Bytecode (.class) Native code Optimizer Run Interpreter
  • 12. Interperter vs JIT • Simplest for of bytecode to machine code translation • Executes 1 bytecode instruction at a time • Repeated every time bytecode is executed • No opportunity to optimize over an instruction set • Easy to implement • Fairly slow • Look at entire or partial context • Optimization decisions based on code graphs analysis • Optimized native code stored in code cache • Runtime profiling – delayed compilation • Compiles hot methods only as compilation is costly
  • 13. JIT Impact on Performance
  • 14. JIT compared to AOT + Advanced optimizations at runtime + Based on profiling + Optimized for target CPU + Global code optimizations + Better cache utilization + Only compile what is really needed (hot) + Reduces long build times - Requires warmup period until reaching peak performance - Increased CPU and memory usage - Non-predictable execution overhead - Optimistic – deoptimizing if wrong
  • 15. JIT and Dynamic Dispatch
  • 17. Classloading Process • Classloaders hierarchy • Initialization order • Laziness • Classpath precedence • Load a class multiple times • Application servers • Multi-versioned dependencies • Insatiate a class via another class • Define dynamic class at runtime Custom Classloaders
  • 18. Lazy Classloading A class or interface typeT will be initialized immediately before the first occurrence of any one of the following: • Instance creation • Static method invocation • Static field read/write (except compile-time constants) +Effective Metaspace (PermGen) management – Can result in degraded performance after startup
  • 19. Classloader Hierarchies •Bootstrap CL loads the internal JVM classes from the java.lang package •The Extension CL (removed in Java 9) loads everything from the java extension directory •The System CL loads everything from the classpath •All user-defined CLs (usually) have the System CL as their parent Extension classloader Bootstrap classloader System classpath classloader …/lib/rt.jar …/lib/ext/*.jar $CLASSPATH
  • 20. Memory Leaks Class Object Classloader Class Class Class Object Object Object Static fields All loaded classes A single object can leak its classloader
  • 22. Memory Access Patterns • Memory access is crucial for performance (locality) • Tradeoff between encapsulation and efficient memory layout (objects vs. primitives) • Method invocation cost • Low level memory manipulation (C-style memory access) • Subverting Java memory structures • Heap vs off-heap (unmanaged) Memory Manipulation
  • 23. Stack vs Heap final class Point { final int x; final int y; } Stack Heap ref header x y Allocated on the Heap More GC
  • 24. Objects Layout final class Point { final int x; final int y; } Point[] pts = header header x y header x y header x y Extra memory for headers Indirection
  • 25. Objects Layout int[] x = header int[] y = header
  • 28. Instance Memory Representation instance 0 mark 4 klass 8 field1 12 field2 … class 0 vtbl ptr 4 layout_helper 8 super_check_offset 12 name 16 secondary_super_cache 20 secondary_supers 24 primary_supers 0 28 primary_supers 1 32 primary_supers 2 36 primary_supers 3 …
  • 29. Memory Types Heap vs Off-heap Memory Heap Off-heap Stack Managed by GC Not Managed By GC Objects Raw bytes
  • 32. Java Agent • Real Black Magic • Bytecode manipulation technique • Plugs into JVM and modifies classes loaded by the class loader • Extremely as powerful as dangerous • Used with JDK up to Java 8, from Java 9 it is available in the JRE
  • 33. Launch Time Instrumentation Class Loader Class Loader Java Agent 1. premain() Transformer .class files 2. register 3. load 5. bytes4. transform JVM MainClass 6. run main() java –javaagent:/to/agent.jar MainClass
  • 34. Other Process JVM 1 Java Agent agentmain() JVM 2 VirtualMachine vm = VirtualMachine.attach("2177"); vm.loadAgent(”/to/agent.jar", ”arg1=1"); pid=2177 Instrumentation
  • 35. Same Process JVM 1 Java Agent agentmain() Instrumentation

Editor's Notes

  1. The JIT compiler is a part of the JVM, which is responsible for compilation done during the execution of a program – at run time – rather than prior to execution. If the compilation is done before the execution, then we speak about Ahead-Of-Time compilation (AOT). The JIT compiler could improve the performance significantly and the flexibility of interpretation remained. The main questions we look answers for: What to compile? (compilation is costly) When to compile? (the ASAP approach is not the best, because we have to gather statistics) How to compile? (different optimization levels, cost-benefit)
  2. Classpath -> order: CP Patching
  3. The delegation model requires that any request for a class loader to load a given class is first delegated to its parent class loader before the requested class loader tries to load the class itself. The parent class loader, in turn, goes through the same process of asking its parent. This chain of delegation continues through to the bootstrap class loader (also known as the primordial or system class loader). If a class loader's parent can load a given class, it returns that class. Otherwise, the class loader attempts to load the class itself.
  4. Classpath -> order: CP Patching