SlideShare une entreprise Scribd logo
1  sur  39
Télécharger pour lire hors ligne
Serkan ÖZAL
JVM UNDER THE HOOD
AGENDA
I. JVM Concepts
II. Memory Management
III. GC
IV. Class Loading
V. Execution Engine
VI. Multi-Threading
VII. JNI
I. JVM CONCEPTS
TERMS
• JVM
• Runs the bytecodes
• Doesn't understand Java source code
• JRE
• Execute java programs
• = JVM + Packages Classes (lang, util, math, ...) + Runtime libraries (native .dll/.so libs)
• JDK
• Compiles and builds java programs
• = JRE + Development/Debugging Tools (javac, javap, javadoc, jdb, …)
HOTSPOT
• Implementation of the JVM
• Originally developed by Sun and now owned by Oracle
• Initially available as an add-on for Java 1.2 (1999)
• Became the default Sun JVM in Java 1.3 (2000)
• = Interpreter + JIT + GC + Class loading + ...
II. MEMORY MANAGEMENT
HEAP MEMORY
NON-HEAP MEMORY
STACK
OBJECT LAYOUT
• Objects are 8 bytes aligned by default
• On JDK 8+, Can be configured by «-XX:ObjectAlignmentInBytes=?»
• Can only be power of 2 between 8-256
• All fields are type aligned
• Fields are packed in the order of their size (except references which are last)
• Sub and parent class fields are never mixed
• Use JOL (Java Object Layout) to analyze object layout
OBJECT SCHEMA
• Objects
• Mark word [4/8 bytes]
• Class pointer [4/8 bytes]
• Fields ...
• Arrays
• Mark word [4/8 bytes]
• Class pointer [4/8 bytes]
• Array length [4 bytes]
• Elements …
COMPRESSED OOPS
• Based on 8x object alignment rule
• Encode/decode by bit shifting (3 bit shift for default (8 bytes) object alignment)
• Can be configured by «-XX:+UseCompressedOops»
• Enabled by default on JDK 7+ (when heap <= 32GB)
• «-XX:+UseCompressedClassPointers» for classes on JDK 8+
OBJECT REFERENCES
• Types of references:
• Strong Reference
• Soft Reference
• Weak Reference
• Phantom Reference
• ReferenceQueue
III. GC
COLLECTION TECHNIQUES
• Copy Collection
• Mark & Sweep (+ Compact) Collection
MINOR GC
• Collects garbage from the Young (Eden + Survivors) space
• Triggered when there is not enough space in Eden for new allocation
• References from Old space to Young space are found via card marking table
MAJOR GC (≅ FULL GC)
• Collects garbage from the Old (Tenured) space
• Mostly involves compaction
• Many Major GCs are triggered by Minor GCs because of promotion failure
• Also targets PermGen (JDK 7-) and Metaspace (JDK 8+)
SERIAL GC
• Uses STW mark-copy collector for Young space
• Uses STW mark-sweep-compact collector for Old space
• Both of these collectors are single-threaded collectors
• Enabled by «-XX:+UseSerialGC»
PARALLEL GC
• Uses STW mark-copy collector for Young space
• Uses STW mark-sweep-compact collector for Old space
• Young space is collected by multi-threaded collector
• Old space is collected by single-threaded collector
• Enabled by «-XX:+UseParallelGC» (default for JDK 8-)
• «-XX:+UseParallelOldGC» for parallel Old space collector
• «-XX:ParallelGCThreads=?» (number of cores by defaults)
CMS
• Uses STW mark-copy collector for Young space
• Uses concurrent mark-sweep collector for Old space
• No compaction normally, but uses free-lists
• FullGC with compaction when “promotion failure”
• Enabled by «-XX:+UseConcMarkSweepGC»
G1
• Heap is split into a number (typically about 2048) smaller heap regions
• The regions that contain the most garbage are collected first
• Evacuation Fully Young
• Remembered Sets
• Humongous regions and objects
• Concurrent marking
• Evacuation Mixed
• Enabled by «-XX:+UseG1GC» (default at JDK 9)
• «–XX:MaxGCPauseMillis=?», default value = 200ms
SHENANDOAH
• JEP 189: Shenandoah: An Ultra-Low-Pause-Time Garbage Collector
• Drived by Red Hat
• First released on Fedore 24 on June 2016
• Not a generational garbage collector
• Concurrent, parallel and region-based garbage collector
• Supports concurrent compaction by Brooks forwarding pointers
IV. CLASS LOADING
CLASS LOADING
• Classes are loaded by classloaders
• Some core classes (java.lang, …) eagerly
• Others lazily when they are first requested
• JVM finds, parses, verifies bytecodes and generates metadata
• Class metadata is saved into Permgen (JDK 7-) / Metaspace (JDK 8+)
• Classes are searched hierarchically through classloaders
• If a class has already been loaded, it returns it
• Otherwise, it delegates the search to the parent class loader
• If the parent class loader does not find the class, tries to find and load the class itself
CLASS LOADER DELEGATION MODEL
V. EXECUTION ENGINE
INTERPRETER
• Converts bytecode into assembly code using a template table
• Template table has assembly code for each bytecode instruction
• Runtime flag «-Xint» can be used to force interpreted mode
• No compiler optimisation is performed
• Start up behaviour for most JVMs
JIT
• JVM continually monitors the code for the following critical metrics:
• Method entry counts
• Loop back branch counts
• Escape Analysis: No Escape, Arg Escape, Global Escape
• CHA: Monomorphic, Bimorphic, Megamorphic calls
• OSR (On-Stack Replacement)
• Inlining
• Intrinsic
• De-optimization
COMPILERS
• C1
• Level 1: no profiling
• Level 2: basic profiling (with invocation and back-edge counters)
• Level 3: full profiling (Inlining, CHA, ...)
• C2
• Level 4: advanced profiling (Loop unrolling, Dead Code Elimination, Escape analysis, ...)
• Tiered (C1 + C2)
• Introduced at JDK 7
• Default since JDK 8
VI. MULTI-THREADING
THREAD MANAGEMENT
• 1:1 mapping between Java threads and native OS threads
• Thread states:
• Internal VM Threads:
• VM Thread
• Periodic Task Thread
• GC Threads
• Compiler Threads
• Signal Dispatcher Thread
• Finalizer Thread
• Reference Handler Thread
• Attach Listener Thread
• ...
• _thread_new
• _thread_in_Java
• _thread_in_vm
• _thread_in_native
• _thread_blocked
SYNCHRONIZATION
• Biased Locking
• Can be disabled by «-XX:-UseBiasedLocking»
• Delay can be configured by «-XX:BiasedLockingStartupDelay»
• Can be rebiased to another thread
• Can be revoked to lightweight lock
• Lightweight Locking
• In case of contention, inflated to heavyweight lock
• Heavyweight Locking
• Uses OS mutex/condition variables
SAFEPOINT
• On safepoint
• All threads running java code (interpreted or compiled) are suspended
• Threads running native code may continue to run as long as they do not
• attempt to contact with JVM via JNI API
• return from native to java
• A thread is at safepoint
• while running JNI code
• if it is blocked, waiting or parked
• A thread is not at safepoint while running java code (interpreted or compiled)
WHEN SAFEPOINTS ARE USED?
• Garbage collection pauses
• Code deoptimization
• Class redefinition (e.g. hot swap or instrumentation)
• Biased lock revocation & Monitor deflation
• Various debug operation (e.g. deadlock check or stacktrace dump)
• Heap dumping
HOW SAFEPOINTS WORK?
• Safepoint check (polling) is implemented as memory reads a barrier
• When safepoint is required, JVM unmaps page with that address provoking page fault
• Safepoint polling exist
• between any 2 bytecodes while running in the interpreter (effectively)
• on non-counted loop back edge in C1/C2 compiled code
• on method return in C1/C2 compiled code.
VII. JNI
HOW TO USE JNI?
• Native libraries are looked up at «java.library.path»
• On Windows, it maps to «PATH»
• On Linux, it maps to «LD_LIBRARY_PATH»
• On OS X, it maps to «DYLD_LIBRARY_PATH»
• (New|Delete)GlobalRef
• (New|Delete)LocalRef
• (Get|Release)???ArrayElements
• (Get|Set)???ArrayRegion
• (Get|Release)(PrimitiveArray|String)Critical
• Exception(Occurred|Check|Clear)
• Use «-Xcheck:jni» for enabling additional checks
CRITICAL NATIVES
• Critical natives can be inlined
• Supported only in HotSpot JVM starting from JDK 7
• Must satisfy the following conditions:
• must be static and not synchronized
• argument types must be primitive or primitive arrays
• implementation must not call JNI functions
• Starts with «JavaCritical_» instead of «Java_»
• You need both critical and standard implementation
THANKS

Contenu connexe

Tendances

Cloud Infrastructures Slide Set 7 - Docker - Neo4j | anynines
Cloud Infrastructures Slide Set 7 - Docker - Neo4j | anyninesCloud Infrastructures Slide Set 7 - Docker - Neo4j | anynines
Cloud Infrastructures Slide Set 7 - Docker - Neo4j | anyninesanynines GmbH
 
MacRuby: What is it? and why should you care?
MacRuby: What is it? and why should you care?MacRuby: What is it? and why should you care?
MacRuby: What is it? and why should you care?Joshua Ballanco
 
JCR In Action (ApacheCon US 2009)
JCR In Action (ApacheCon US 2009)JCR In Action (ApacheCon US 2009)
JCR In Action (ApacheCon US 2009)Carsten Ziegeler
 
Jslab rssh: JS as language platform
Jslab rssh:  JS as language platformJslab rssh:  JS as language platform
Jslab rssh: JS as language platformRuslan Shevchenko
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Haim Yadid
 
oracle linux administration | oracle linux training - oracle trainings
oracle linux administration | oracle linux training - oracle trainingsoracle linux administration | oracle linux training - oracle trainings
oracle linux administration | oracle linux training - oracle trainingsOnlineOracleTrainings
 
Transactions and Concurrency Control Patterns
Transactions and Concurrency Control PatternsTransactions and Concurrency Control Patterns
Transactions and Concurrency Control PatternsVlad Mihalcea
 
The architecture of oak
The architecture of oakThe architecture of oak
The architecture of oakMichael Dürig
 

Tendances (13)

the windows opereting system
the windows opereting systemthe windows opereting system
the windows opereting system
 
Cloud Infrastructures Slide Set 7 - Docker - Neo4j | anynines
Cloud Infrastructures Slide Set 7 - Docker - Neo4j | anyninesCloud Infrastructures Slide Set 7 - Docker - Neo4j | anynines
Cloud Infrastructures Slide Set 7 - Docker - Neo4j | anynines
 
Earhart
EarhartEarhart
Earhart
 
IDLs
IDLsIDLs
IDLs
 
MacRuby: What is it? and why should you care?
MacRuby: What is it? and why should you care?MacRuby: What is it? and why should you care?
MacRuby: What is it? and why should you care?
 
JCR In Action (ApacheCon US 2009)
JCR In Action (ApacheCon US 2009)JCR In Action (ApacheCon US 2009)
JCR In Action (ApacheCon US 2009)
 
Jslab rssh: JS as language platform
Jslab rssh:  JS as language platformJslab rssh:  JS as language platform
Jslab rssh: JS as language platform
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
oracle linux administration | oracle linux training - oracle trainings
oracle linux administration | oracle linux training - oracle trainingsoracle linux administration | oracle linux training - oracle trainings
oracle linux administration | oracle linux training - oracle trainings
 
Transactions and Concurrency Control Patterns
Transactions and Concurrency Control PatternsTransactions and Concurrency Control Patterns
Transactions and Concurrency Control Patterns
 
Scala profiling
Scala profilingScala profiling
Scala profiling
 
Java 9 sneak peek
Java 9 sneak peekJava 9 sneak peek
Java 9 sneak peek
 
The architecture of oak
The architecture of oakThe architecture of oak
The architecture of oak
 

Similaire à JVM Under the Hood

Java Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVMJava Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVModnoklassniki.ru
 
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 JVMAlex Birch
 
Clr jvm implementation differences
Clr jvm implementation differencesClr jvm implementation differences
Clr jvm implementation differencesJean-Philippe BEMPEL
 
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
 
Jvm lecture
Jvm lectureJvm lecture
Jvm lecturesdslnmd
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoringSimon Ritter
 
How Class Data Sharing Can Speed up Your Jakarta EE Application Startup
How Class Data Sharing Can Speed up Your Jakarta EE Application StartupHow Class Data Sharing Can Speed up Your Jakarta EE Application Startup
How Class Data Sharing Can Speed up Your Jakarta EE Application StartupRudy De Busscher
 
An Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAn Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAbhishek Asthana
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesAlexandra Masterson
 
Introduction to java by priti sajja
Introduction to java by priti sajjaIntroduction to java by priti sajja
Introduction to java by priti sajjaPriti Srinivas Sajja
 
Ahead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsAhead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsNikita Lipsky
 
Java Garbage Collector and The Memory Model
Java Garbage Collector and The Memory ModelJava Garbage Collector and The Memory Model
Java Garbage Collector and The Memory ModelErnesto Arroyo Ron
 
Metasploit & Windows Kernel Exploitation
Metasploit & Windows Kernel ExploitationMetasploit & Windows Kernel Exploitation
Metasploit & Windows Kernel ExploitationzeroSteiner
 
Tomcatx troubleshooting-production
Tomcatx troubleshooting-productionTomcatx troubleshooting-production
Tomcatx troubleshooting-productionVladimir Khokhryakov
 
Spil Storage Platform (Erlang) @ EUG-NL
Spil Storage Platform (Erlang) @ EUG-NLSpil Storage Platform (Erlang) @ EUG-NL
Spil Storage Platform (Erlang) @ EUG-NLThijs Terlouw
 
JAVA-History-buzzwords-JVM_architecture.pptx
JAVA-History-buzzwords-JVM_architecture.pptxJAVA-History-buzzwords-JVM_architecture.pptx
JAVA-History-buzzwords-JVM_architecture.pptx20EUEE018DEEPAKM
 
Getting Started with Java
Getting Started with JavaGetting Started with Java
Getting Started with JavaMichael Redlich
 

Similaire à JVM Under the Hood (20)

Java Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVMJava Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVM
 
Optimizing Java Notes
Optimizing Java NotesOptimizing Java Notes
Optimizing Java Notes
 
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
 
Clr jvm implementation differences
Clr jvm implementation differencesClr jvm implementation differences
Clr jvm implementation differences
 
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
 
Java goes wild, lesson 1
Java goes wild, lesson 1Java goes wild, lesson 1
Java goes wild, lesson 1
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Jvm lecture
Jvm lectureJvm lecture
Jvm lecture
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoring
 
How Class Data Sharing Can Speed up Your Jakarta EE Application Startup
How Class Data Sharing Can Speed up Your Jakarta EE Application StartupHow Class Data Sharing Can Speed up Your Jakarta EE Application Startup
How Class Data Sharing Can Speed up Your Jakarta EE Application Startup
 
An Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAn Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in Java
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Introduction to java by priti sajja
Introduction to java by priti sajjaIntroduction to java by priti sajja
Introduction to java by priti sajja
 
Ahead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsAhead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java Applications
 
Java Garbage Collector and The Memory Model
Java Garbage Collector and The Memory ModelJava Garbage Collector and The Memory Model
Java Garbage Collector and The Memory Model
 
Metasploit & Windows Kernel Exploitation
Metasploit & Windows Kernel ExploitationMetasploit & Windows Kernel Exploitation
Metasploit & Windows Kernel Exploitation
 
Tomcatx troubleshooting-production
Tomcatx troubleshooting-productionTomcatx troubleshooting-production
Tomcatx troubleshooting-production
 
Spil Storage Platform (Erlang) @ EUG-NL
Spil Storage Platform (Erlang) @ EUG-NLSpil Storage Platform (Erlang) @ EUG-NL
Spil Storage Platform (Erlang) @ EUG-NL
 
JAVA-History-buzzwords-JVM_architecture.pptx
JAVA-History-buzzwords-JVM_architecture.pptxJAVA-History-buzzwords-JVM_architecture.pptx
JAVA-History-buzzwords-JVM_architecture.pptx
 
Getting Started with Java
Getting Started with JavaGetting Started with Java
Getting Started with Java
 

Plus de Serkan Özal

Flying Server-less on the Cloud with AWS Lambda
Flying Server-less on the Cloud with AWS LambdaFlying Server-less on the Cloud with AWS Lambda
Flying Server-less on the Cloud with AWS LambdaSerkan Özal
 
Improving performance of decision support queries in columnar cloud database ...
Improving performance of decision support queries in columnar cloud database ...Improving performance of decision support queries in columnar cloud database ...
Improving performance of decision support queries in columnar cloud database ...Serkan Özal
 
Ankara JUG Big Data Presentation
Ankara JUG Big Data PresentationAnkara JUG Big Data Presentation
Ankara JUG Big Data PresentationSerkan Özal
 
AWS EMR - Amazon Elastic Map Reduce
AWS EMR - Amazon Elastic Map ReduceAWS EMR - Amazon Elastic Map Reduce
AWS EMR - Amazon Elastic Map ReduceSerkan Özal
 

Plus de Serkan Özal (7)

Flying Server-less on the Cloud with AWS Lambda
Flying Server-less on the Cloud with AWS LambdaFlying Server-less on the Cloud with AWS Lambda
Flying Server-less on the Cloud with AWS Lambda
 
MySafe
MySafeMySafe
MySafe
 
Improving performance of decision support queries in columnar cloud database ...
Improving performance of decision support queries in columnar cloud database ...Improving performance of decision support queries in columnar cloud database ...
Improving performance of decision support queries in columnar cloud database ...
 
Big data on aws
Big data on awsBig data on aws
Big data on aws
 
Ankara JUG Big Data Presentation
Ankara JUG Big Data PresentationAnkara JUG Big Data Presentation
Ankara JUG Big Data Presentation
 
AWS EMR - Amazon Elastic Map Reduce
AWS EMR - Amazon Elastic Map ReduceAWS EMR - Amazon Elastic Map Reduce
AWS EMR - Amazon Elastic Map Reduce
 
Big data concepts
Big data conceptsBig data concepts
Big data concepts
 

Dernier

Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Data modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainData modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainAbdul Ahad
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Copilot para Microsoft 365 y Power Platform Copilot
Copilot para Microsoft 365 y Power Platform CopilotCopilot para Microsoft 365 y Power Platform Copilot
Copilot para Microsoft 365 y Power Platform CopilotEdgard Alejos
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 

Dernier (20)

Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Data modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainData modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software Domain
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Copilot para Microsoft 365 y Power Platform Copilot
Copilot para Microsoft 365 y Power Platform CopilotCopilot para Microsoft 365 y Power Platform Copilot
Copilot para Microsoft 365 y Power Platform Copilot
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 

JVM Under the Hood

  • 2. AGENDA I. JVM Concepts II. Memory Management III. GC IV. Class Loading V. Execution Engine VI. Multi-Threading VII. JNI
  • 4. TERMS • JVM • Runs the bytecodes • Doesn't understand Java source code • JRE • Execute java programs • = JVM + Packages Classes (lang, util, math, ...) + Runtime libraries (native .dll/.so libs) • JDK • Compiles and builds java programs • = JRE + Development/Debugging Tools (javac, javap, javadoc, jdb, …)
  • 5. HOTSPOT • Implementation of the JVM • Originally developed by Sun and now owned by Oracle • Initially available as an add-on for Java 1.2 (1999) • Became the default Sun JVM in Java 1.3 (2000) • = Interpreter + JIT + GC + Class loading + ...
  • 10. OBJECT LAYOUT • Objects are 8 bytes aligned by default • On JDK 8+, Can be configured by «-XX:ObjectAlignmentInBytes=?» • Can only be power of 2 between 8-256 • All fields are type aligned • Fields are packed in the order of their size (except references which are last) • Sub and parent class fields are never mixed • Use JOL (Java Object Layout) to analyze object layout
  • 11. OBJECT SCHEMA • Objects • Mark word [4/8 bytes] • Class pointer [4/8 bytes] • Fields ... • Arrays • Mark word [4/8 bytes] • Class pointer [4/8 bytes] • Array length [4 bytes] • Elements …
  • 12. COMPRESSED OOPS • Based on 8x object alignment rule • Encode/decode by bit shifting (3 bit shift for default (8 bytes) object alignment) • Can be configured by «-XX:+UseCompressedOops» • Enabled by default on JDK 7+ (when heap <= 32GB) • «-XX:+UseCompressedClassPointers» for classes on JDK 8+
  • 13. OBJECT REFERENCES • Types of references: • Strong Reference • Soft Reference • Weak Reference • Phantom Reference • ReferenceQueue
  • 15. COLLECTION TECHNIQUES • Copy Collection • Mark & Sweep (+ Compact) Collection
  • 16. MINOR GC • Collects garbage from the Young (Eden + Survivors) space • Triggered when there is not enough space in Eden for new allocation • References from Old space to Young space are found via card marking table
  • 17. MAJOR GC (≅ FULL GC) • Collects garbage from the Old (Tenured) space • Mostly involves compaction • Many Major GCs are triggered by Minor GCs because of promotion failure • Also targets PermGen (JDK 7-) and Metaspace (JDK 8+)
  • 18. SERIAL GC • Uses STW mark-copy collector for Young space • Uses STW mark-sweep-compact collector for Old space • Both of these collectors are single-threaded collectors • Enabled by «-XX:+UseSerialGC»
  • 19. PARALLEL GC • Uses STW mark-copy collector for Young space • Uses STW mark-sweep-compact collector for Old space • Young space is collected by multi-threaded collector • Old space is collected by single-threaded collector • Enabled by «-XX:+UseParallelGC» (default for JDK 8-) • «-XX:+UseParallelOldGC» for parallel Old space collector • «-XX:ParallelGCThreads=?» (number of cores by defaults)
  • 20. CMS • Uses STW mark-copy collector for Young space • Uses concurrent mark-sweep collector for Old space • No compaction normally, but uses free-lists • FullGC with compaction when “promotion failure” • Enabled by «-XX:+UseConcMarkSweepGC»
  • 21. G1 • Heap is split into a number (typically about 2048) smaller heap regions • The regions that contain the most garbage are collected first • Evacuation Fully Young • Remembered Sets • Humongous regions and objects • Concurrent marking • Evacuation Mixed • Enabled by «-XX:+UseG1GC» (default at JDK 9) • «–XX:MaxGCPauseMillis=?», default value = 200ms
  • 22. SHENANDOAH • JEP 189: Shenandoah: An Ultra-Low-Pause-Time Garbage Collector • Drived by Red Hat • First released on Fedore 24 on June 2016 • Not a generational garbage collector • Concurrent, parallel and region-based garbage collector • Supports concurrent compaction by Brooks forwarding pointers
  • 24. CLASS LOADING • Classes are loaded by classloaders • Some core classes (java.lang, …) eagerly • Others lazily when they are first requested • JVM finds, parses, verifies bytecodes and generates metadata • Class metadata is saved into Permgen (JDK 7-) / Metaspace (JDK 8+) • Classes are searched hierarchically through classloaders • If a class has already been loaded, it returns it • Otherwise, it delegates the search to the parent class loader • If the parent class loader does not find the class, tries to find and load the class itself
  • 27. INTERPRETER • Converts bytecode into assembly code using a template table • Template table has assembly code for each bytecode instruction • Runtime flag «-Xint» can be used to force interpreted mode • No compiler optimisation is performed • Start up behaviour for most JVMs
  • 28. JIT • JVM continually monitors the code for the following critical metrics: • Method entry counts • Loop back branch counts • Escape Analysis: No Escape, Arg Escape, Global Escape • CHA: Monomorphic, Bimorphic, Megamorphic calls • OSR (On-Stack Replacement) • Inlining • Intrinsic • De-optimization
  • 29. COMPILERS • C1 • Level 1: no profiling • Level 2: basic profiling (with invocation and back-edge counters) • Level 3: full profiling (Inlining, CHA, ...) • C2 • Level 4: advanced profiling (Loop unrolling, Dead Code Elimination, Escape analysis, ...) • Tiered (C1 + C2) • Introduced at JDK 7 • Default since JDK 8
  • 31. THREAD MANAGEMENT • 1:1 mapping between Java threads and native OS threads • Thread states: • Internal VM Threads: • VM Thread • Periodic Task Thread • GC Threads • Compiler Threads • Signal Dispatcher Thread • Finalizer Thread • Reference Handler Thread • Attach Listener Thread • ... • _thread_new • _thread_in_Java • _thread_in_vm • _thread_in_native • _thread_blocked
  • 32. SYNCHRONIZATION • Biased Locking • Can be disabled by «-XX:-UseBiasedLocking» • Delay can be configured by «-XX:BiasedLockingStartupDelay» • Can be rebiased to another thread • Can be revoked to lightweight lock • Lightweight Locking • In case of contention, inflated to heavyweight lock • Heavyweight Locking • Uses OS mutex/condition variables
  • 33. SAFEPOINT • On safepoint • All threads running java code (interpreted or compiled) are suspended • Threads running native code may continue to run as long as they do not • attempt to contact with JVM via JNI API • return from native to java • A thread is at safepoint • while running JNI code • if it is blocked, waiting or parked • A thread is not at safepoint while running java code (interpreted or compiled)
  • 34. WHEN SAFEPOINTS ARE USED? • Garbage collection pauses • Code deoptimization • Class redefinition (e.g. hot swap or instrumentation) • Biased lock revocation & Monitor deflation • Various debug operation (e.g. deadlock check or stacktrace dump) • Heap dumping
  • 35. HOW SAFEPOINTS WORK? • Safepoint check (polling) is implemented as memory reads a barrier • When safepoint is required, JVM unmaps page with that address provoking page fault • Safepoint polling exist • between any 2 bytecodes while running in the interpreter (effectively) • on non-counted loop back edge in C1/C2 compiled code • on method return in C1/C2 compiled code.
  • 37. HOW TO USE JNI? • Native libraries are looked up at «java.library.path» • On Windows, it maps to «PATH» • On Linux, it maps to «LD_LIBRARY_PATH» • On OS X, it maps to «DYLD_LIBRARY_PATH» • (New|Delete)GlobalRef • (New|Delete)LocalRef • (Get|Release)???ArrayElements • (Get|Set)???ArrayRegion • (Get|Release)(PrimitiveArray|String)Critical • Exception(Occurred|Check|Clear) • Use «-Xcheck:jni» for enabling additional checks
  • 38. CRITICAL NATIVES • Critical natives can be inlined • Supported only in HotSpot JVM starting from JDK 7 • Must satisfy the following conditions: • must be static and not synchronized • argument types must be primitive or primitive arrays • implementation must not call JNI functions • Starts with «JavaCritical_» instead of «Java_» • You need both critical and standard implementation