SlideShare ist ein Scribd-Unternehmen logo
1 von 28
An Introduction to
JVM internals
and
Garbage Collection
Abhishek Asthana
Senior Member of Tech Staff
Oracle
Java Memory Structure
Heap Space
Method Area /
Permanent Gen
Native Area
Method Area Structure
Reserved
Runtime Constant Pool
Field and Method Data
Code
-XX:PermSize
-XX:MaxPermSize
Method Area
• Stores per-class structures such as the run-
time constant pool, field and method data,
and the code for methods and constructors.
• Run-time Constant Pool: contains several
kinds of constants, ranging from numeric
literals known at compile-time to method and
field references that must be resolved at run-
time.
Native Area Structure
Thread 1 … N
Program Counter
(PC) Register
Thread Stack Native Stack
Native Area
• PC Register: Contains "address of the
instruction currently being executed". If
current method is native, its value is
undefined.
• Thread Stack: stores frames (local variables of
primitive types, object references and partial
results) and plays a part in method invocation
and return.
• Native Stack: support native methods.
Example (what goes where!)
Heap Method Area Thread Stack
Object: FileInputStream Class: FileTest Reference: stream
Object: Scanner Class: FileInputStream Reference: scanner
Object: String Class: Scanner Reference: line
Object: Exception Class: Exception Reference: e
Example (what goes where!)
OutOfMemoryError – but where?
• Exception in thread “main”:
java.lang.OutOfMemoryError: Java heap space
Reason: an object could not be allocated into the heap space.
• Exception in thread “main”:
java.lang.OutOfMemoryError: PermGen space
Reason: classes and methods could not be loaded into the
PermGen space. This occurs when an application requires a lot
of classes e.g. in various 3rd party libraries.
• Exception in thread “main”:
java.lang.OutOfMemoryError: Requested
array size exceeds VM limit
Reason: this occurs when an arrays is created larger than the
heap size.
• Exception in thread “main”:
java.lang.OutOfMemoryError: (Native
method)
Reason: this error indicates that the problem originates from
a native call rather than in the JVM.
OutOfMemoryError – but where?
Garbage Collection Concepts
A garbage collector is responsible for
– allocating memory
– ensuring that any referenced objects remain in memory
– recovering memory used by objects that are no longer
reachable from references in executing code.
• Objects that are referenced are said to be live
• Objects that are no longer referenced are
considered dead and are termed garbage.
Garbage Collection Concepts
• GC Roots
• Class and static variables - class
loaded by system class loader.
• Thread - live thread
• Stack Local - local variable or
parameter of Java method
• JNI Local - local variable or
parameter of JNI method
• JNI Global - global JNI reference
• Monitor Used - objects used as a
monitor for synchronization
• Held by JVM - objects held from
garbage collection by JVM for its
purposes.
GC Roots
Desirable GC Features
• Safe: live data must never be erroneously
freed.
• Comprehensive: garbage should not remain
unclaimed for more than a small number of
collection cycles.
• Efficient: No long pauses during which the
application is not running.
• Limit fragmentation: Avoid memory
fragmentation.
GC Design Choices
• Serial vs Parallel
• Concurrent vs Stop-the-World
• Compacting : moving all the live objects together
and completely reclaiming the remaining memory.
vs
• Non-Compacting : releases the space utilized by
garbage objects in-place
vs
• Copying : copies live objects to a different memory
area.
Key performance metrics
• Throughput: % of total time not spent in garbage collection,
considered over long periods of time.
• Pauses: times when an application appears unresponsive
because GC is occurring.
• Frequency of collection: how often collection occurs,
relative to application execution.
• Promptness: time between when an object is dead and
when memory is reclaimed.
• Footprint: working set of a process, measured in pages and
cache lines.
• Generations: separate pools holding objects
of different ages.
• Weak Generational Hypothesis:
– Most allocated objects die young.
– Few references from older to younger objects
exist.
Generational Collection
Young Generation
Old/Tenured
ReservedOld Generation
Eden
S
2
S
1
-Xms
-Xmx
-XX:MaxNewSize
-XX:NewSize
Java Heap Space StructureReserved
PermGen
Reserved
Permanent Generation
Young Generation Collection
S2Eden
Empty
Empty
O1
O2
O3
O4
O5
Empty
Empty
O2
O3
O5
O1
O4
S1
After Minor GC 1
Young Generation Collection
Empty
Empty
O2
O3
O5
O6
O7
O8
O9
O10
O5
O7
O10
Eden S1 S2
Empty
Empty
O2
O3
O6
O8
O9
Eden S1 S2
After Minor GC2
Old (and Perm) Generation
Collection
• mark-sweep-compact collection algorithm.
• Mark: the collector identifies which objects
are still live.
• Sweep: “sweeps” over the generations,
identifying garbage.
• Compact: The collector then performs sliding
compaction, sliding the live objects towards
the beginning of the old generation
Comparing GC Strategies
Pause
Pause
Concurrent Mark
Re-Mark
Serial Parallel Concurrent
Application Thread GC Thread
Parallel Collector
• Minor GC: uses a parallel version of the minor
GC algorithm utilized by the Serial Collector.
– Reduced pause times.
• Full GC: same as Serial Collector
– (mark-sweep-compact)
• can be explicitly requested by using
- XX:+UseParallelGC command line option
Parallel Compacting Collector
• Minor GC: same algorithm as parallel
collector.
• Full GC: same as Serial Collector
– (mark-sweep-compact)
• can be explicitly requested by using
- XX:+UseParallelGC command line option
CMS Collector
• Concurrent Mark and Sweep
1. Initial marking: GC root objects marked alive.
Complete ‘Stop-the-World’.
2. Concurrent marking: marked root objects are
traversed and all reachable objects are
marked. Another round of marking of objects
allocated during this phase!
3. Final marking: Stop-the-World and all remaining
newly allocated objects are marked alive.
4. Sweep!
Collection of Garbage
Garbage Collector!
Garbage First (G1) Collector
• The heap is partitioned into a set of equal-sized
heap regions, each a contiguous range of virtual
memory
• Concurrent marking phase to determine liveness
of objects across the heap.
• After the mark phase completes, G1 focuses on
the regions that are likely to be full of garbage.
• Copies objects to a single region on the heap, and
in the process both compacts and frees up
memory
JConsole
Thank You!

Weitere ähnliche Inhalte

Was ist angesagt?

Java gc
Java gcJava gc
Java gcNiit
 
Understanding Java Garbage Collection - And What You Can Do About It
Understanding Java Garbage Collection - And What You Can Do About ItUnderstanding Java Garbage Collection - And What You Can Do About It
Understanding Java Garbage Collection - And What You Can Do About ItAzul Systems Inc.
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunningguest1f2740
 
Java Performance Monitoring & Tuning
Java Performance Monitoring & TuningJava Performance Monitoring & Tuning
Java Performance Monitoring & TuningMuhammed Shakir
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance TuningMinh Hoang
 
JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020Joseph Kuo
 
Java Serialization Facts and Fallacies
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and FallaciesRoman Elizarov
 
JVM @ Taobao - QCon Hangzhou 2011
JVM @ Taobao - QCon Hangzhou 2011JVM @ Taobao - QCon Hangzhou 2011
JVM @ Taobao - QCon Hangzhou 2011Kris Mok
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waitingRoman Elizarov
 
Jvm profiling under the hood
Jvm profiling under the hoodJvm profiling under the hood
Jvm profiling under the hoodRichardWarburton
 
Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)RichardWarburton
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?Roman Elizarov
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript EngineKris Mok
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictabilityRichardWarburton
 
Lock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin CoroutinesLock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin CoroutinesRoman Elizarov
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 

Was ist angesagt? (20)

Java gc
Java gcJava gc
Java gc
 
Understanding Java Garbage Collection - And What You Can Do About It
Understanding Java Garbage Collection - And What You Can Do About ItUnderstanding Java Garbage Collection - And What You Can Do About It
Understanding Java Garbage Collection - And What You Can Do About It
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
 
Java Performance Monitoring & Tuning
Java Performance Monitoring & TuningJava Performance Monitoring & Tuning
Java Performance Monitoring & Tuning
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020
 
Java Serialization Facts and Fallacies
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and Fallacies
 
JVM @ Taobao - QCon Hangzhou 2011
JVM @ Taobao - QCon Hangzhou 2011JVM @ Taobao - QCon Hangzhou 2011
JVM @ Taobao - QCon Hangzhou 2011
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waiting
 
Jvm profiling under the hood
Jvm profiling under the hoodJvm profiling under the hood
Jvm profiling under the hood
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
RxJava@DAUG
RxJava@DAUGRxJava@DAUG
RxJava@DAUG
 
Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)
 
Basanta jtr2009
Basanta jtr2009Basanta jtr2009
Basanta jtr2009
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript Engine
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Lock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin CoroutinesLock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin Coroutines
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 

Andere mochten auch

Алгоритмы поиска и сортировки
Алгоритмы  поиска и сортировкиАлгоритмы  поиска и сортировки
Алгоритмы поиска и сортировкиUnguryan Vitaliy
 
Java. Cистемы счислния, битовые операции
Java. Cистемы счислния, битовые операцииJava. Cистемы счислния, битовые операции
Java. Cистемы счислния, битовые операцииUnguryan Vitaliy
 
Java. Логические операторы, операторы ветвления.
Java. Логические операторы, операторы ветвления.Java. Логические операторы, операторы ветвления.
Java. Логические операторы, операторы ветвления.Unguryan Vitaliy
 
Java. Интерфейс Reference - типы ссылок
Java. Интерфейс Reference -  типы ссылокJava. Интерфейс Reference -  типы ссылок
Java. Интерфейс Reference - типы ссылокUnguryan Vitaliy
 
Java. Полиморфизм.
Java. Полиморфизм.Java. Полиморфизм.
Java. Полиморфизм.Unguryan Vitaliy
 
Java. Инкапсуляция.
Java. Инкапсуляция.Java. Инкапсуляция.
Java. Инкапсуляция.Unguryan Vitaliy
 
Java. Строки. Класс String.
Java. Строки. Класс String.Java. Строки. Класс String.
Java. Строки. Класс String.Unguryan Vitaliy
 
Java. Интерфейс Map - ассоциативные массивы.
Java. Интерфейс Map - ассоциативные массивы.Java. Интерфейс Map - ассоциативные массивы.
Java. Интерфейс Map - ассоциативные массивы.Unguryan Vitaliy
 
Java. Наследование.
Java. Наследование.Java. Наследование.
Java. Наследование.Unguryan Vitaliy
 
Java. Введение в коллекции. Классы обертки. Перечисленияю
Java. Введение в коллекции. Классы обертки.  ПеречисленияюJava. Введение в коллекции. Классы обертки.  Перечисленияю
Java. Введение в коллекции. Классы обертки. ПеречисленияюUnguryan Vitaliy
 
Java. Сборщик мусора. Работа с памятью.
Java.  Сборщик мусора. Работа с памятью. Java.  Сборщик мусора. Работа с памятью.
Java. Сборщик мусора. Работа с памятью. Unguryan Vitaliy
 
Java. Generic - шаблонные типы.
Java.  Generic - шаблонные типы.Java.  Generic - шаблонные типы.
Java. Generic - шаблонные типы.Unguryan Vitaliy
 
Java. Вложенные классы и интерфейсы.
Java. Вложенные классы и интерфейсы.Java. Вложенные классы и интерфейсы.
Java. Вложенные классы и интерфейсы.Unguryan Vitaliy
 
Java. Массивы. Многомерные массивы.
Java. Массивы. Многомерные массивы.Java. Массивы. Многомерные массивы.
Java. Массивы. Многомерные массивы.Unguryan Vitaliy
 
Исключения и ошибки
Исключения и ошибкиИсключения и ошибки
Исключения и ошибкиUnguryan Vitaliy
 
Java. Конструкторы класса и инициализация
Java. Конструкторы класса и инициализация Java. Конструкторы класса и инициализация
Java. Конструкторы класса и инициализация Unguryan Vitaliy
 

Andere mochten auch (20)

Алгоритмы поиска и сортировки
Алгоритмы  поиска и сортировкиАлгоритмы  поиска и сортировки
Алгоритмы поиска и сортировки
 
Java. Cистемы счислния, битовые операции
Java. Cистемы счислния, битовые операцииJava. Cистемы счислния, битовые операции
Java. Cистемы счислния, битовые операции
 
Java. Логические операторы, операторы ветвления.
Java. Логические операторы, операторы ветвления.Java. Логические операторы, операторы ветвления.
Java. Логические операторы, операторы ветвления.
 
Java. Интерфейс Reference - типы ссылок
Java. Интерфейс Reference -  типы ссылокJava. Интерфейс Reference -  типы ссылок
Java. Интерфейс Reference - типы ссылок
 
Java. Полиморфизм.
Java. Полиморфизм.Java. Полиморфизм.
Java. Полиморфизм.
 
Java. Циклы.
Java. Циклы.Java. Циклы.
Java. Циклы.
 
Java. Инкапсуляция.
Java. Инкапсуляция.Java. Инкапсуляция.
Java. Инкапсуляция.
 
Java. Строки. Класс String.
Java. Строки. Класс String.Java. Строки. Класс String.
Java. Строки. Класс String.
 
Uml
UmlUml
Uml
 
Java. Интерфейс Map - ассоциативные массивы.
Java. Интерфейс Map - ассоциативные массивы.Java. Интерфейс Map - ассоциативные массивы.
Java. Интерфейс Map - ассоциативные массивы.
 
Java. Наследование.
Java. Наследование.Java. Наследование.
Java. Наследование.
 
Java. Введение в коллекции. Классы обертки. Перечисленияю
Java. Введение в коллекции. Классы обертки.  ПеречисленияюJava. Введение в коллекции. Классы обертки.  Перечисленияю
Java. Введение в коллекции. Классы обертки. Перечисленияю
 
Java. Сборщик мусора. Работа с памятью.
Java.  Сборщик мусора. Работа с памятью. Java.  Сборщик мусора. Работа с памятью.
Java. Сборщик мусора. Работа с памятью.
 
Java. Generic - шаблонные типы.
Java.  Generic - шаблонные типы.Java.  Generic - шаблонные типы.
Java. Generic - шаблонные типы.
 
Java. Методы
Java. Методы Java. Методы
Java. Методы
 
Java. Вложенные классы и интерфейсы.
Java. Вложенные классы и интерфейсы.Java. Вложенные классы и интерфейсы.
Java. Вложенные классы и интерфейсы.
 
Java. Массивы. Многомерные массивы.
Java. Массивы. Многомерные массивы.Java. Массивы. Многомерные массивы.
Java. Массивы. Многомерные массивы.
 
Исключения и ошибки
Исключения и ошибкиИсключения и ошибки
Исключения и ошибки
 
List - списки
List - списки List - списки
List - списки
 
Java. Конструкторы класса и инициализация
Java. Конструкторы класса и инициализация Java. Конструкторы класса и инициализация
Java. Конструкторы класса и инициализация
 

Ähnlich wie An Introduction to JVM Internals and Garbage Collection in Java

Jvm lecture
Jvm lectureJvm lecture
Jvm lecturesdslnmd
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionHaribabu Nandyal Padmanaban
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Ryan Cuprak
 
Garbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMGarbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMjaganmohanreddyk
 
«Большие объёмы данных и сборка мусора в Java
«Большие объёмы данных и сборка мусора в Java«Большие объёмы данных и сборка мусора в Java
«Большие объёмы данных и сборка мусора в JavaOlga Lavrentieva
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
G1 collector and tuning and Cassandra
G1 collector and tuning and CassandraG1 collector and tuning and Cassandra
G1 collector and tuning and CassandraChris Lohfink
 
.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4aminmesbahi
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9Gal Marder
 
Everything I Ever Learned About JVM Performance Tuning @Twitter
Everything I Ever Learned About JVM Performance Tuning @TwitterEverything I Ever Learned About JVM Performance Tuning @Twitter
Everything I Ever Learned About JVM Performance Tuning @TwitterAttila Szegedi
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuningosa_ora
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoringSimon Ritter
 
OpenJDK Concurrent Collectors
OpenJDK Concurrent CollectorsOpenJDK Concurrent Collectors
OpenJDK Concurrent CollectorsMonica Beckwith
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugketan_patel25
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performanceRoger Xia
 
.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves.NET UY Meetup
 
Memory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineMemory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineAndrew Case
 
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
 

Ähnlich wie An Introduction to JVM Internals and Garbage Collection in Java (20)

Jvm lecture
Jvm lectureJvm lecture
Jvm lecture
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage Collection
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
Garbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMGarbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVM
 
«Большие объёмы данных и сборка мусора в Java
«Большие объёмы данных и сборка мусора в Java«Большие объёмы данных и сборка мусора в Java
«Большие объёмы данных и сборка мусора в Java
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
G1 collector and tuning and Cassandra
G1 collector and tuning and CassandraG1 collector and tuning and Cassandra
G1 collector and tuning and Cassandra
 
.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
Javasession10
Javasession10Javasession10
Javasession10
 
Everything I Ever Learned About JVM Performance Tuning @Twitter
Everything I Ever Learned About JVM Performance Tuning @TwitterEverything I Ever Learned About JVM Performance Tuning @Twitter
Everything I Ever Learned About JVM Performance Tuning @Twitter
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoring
 
OpenJDK Concurrent Collectors
OpenJDK Concurrent CollectorsOpenJDK Concurrent Collectors
OpenJDK Concurrent Collectors
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
 
.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves
 
Memory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineMemory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual Machine
 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVM
 
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
 

Kürzlich hochgeladen

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Kürzlich hochgeladen (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

An Introduction to JVM Internals and Garbage Collection in Java

  • 1. An Introduction to JVM internals and Garbage Collection Abhishek Asthana Senior Member of Tech Staff Oracle
  • 2. Java Memory Structure Heap Space Method Area / Permanent Gen Native Area
  • 3. Method Area Structure Reserved Runtime Constant Pool Field and Method Data Code -XX:PermSize -XX:MaxPermSize
  • 4. Method Area • Stores per-class structures such as the run- time constant pool, field and method data, and the code for methods and constructors. • Run-time Constant Pool: contains several kinds of constants, ranging from numeric literals known at compile-time to method and field references that must be resolved at run- time.
  • 5. Native Area Structure Thread 1 … N Program Counter (PC) Register Thread Stack Native Stack
  • 6. Native Area • PC Register: Contains "address of the instruction currently being executed". If current method is native, its value is undefined. • Thread Stack: stores frames (local variables of primitive types, object references and partial results) and plays a part in method invocation and return. • Native Stack: support native methods.
  • 8. Heap Method Area Thread Stack Object: FileInputStream Class: FileTest Reference: stream Object: Scanner Class: FileInputStream Reference: scanner Object: String Class: Scanner Reference: line Object: Exception Class: Exception Reference: e Example (what goes where!)
  • 9. OutOfMemoryError – but where? • Exception in thread “main”: java.lang.OutOfMemoryError: Java heap space Reason: an object could not be allocated into the heap space. • Exception in thread “main”: java.lang.OutOfMemoryError: PermGen space Reason: classes and methods could not be loaded into the PermGen space. This occurs when an application requires a lot of classes e.g. in various 3rd party libraries.
  • 10. • Exception in thread “main”: java.lang.OutOfMemoryError: Requested array size exceeds VM limit Reason: this occurs when an arrays is created larger than the heap size. • Exception in thread “main”: java.lang.OutOfMemoryError: (Native method) Reason: this error indicates that the problem originates from a native call rather than in the JVM. OutOfMemoryError – but where?
  • 11. Garbage Collection Concepts A garbage collector is responsible for – allocating memory – ensuring that any referenced objects remain in memory – recovering memory used by objects that are no longer reachable from references in executing code. • Objects that are referenced are said to be live • Objects that are no longer referenced are considered dead and are termed garbage.
  • 12. Garbage Collection Concepts • GC Roots • Class and static variables - class loaded by system class loader. • Thread - live thread • Stack Local - local variable or parameter of Java method • JNI Local - local variable or parameter of JNI method • JNI Global - global JNI reference • Monitor Used - objects used as a monitor for synchronization • Held by JVM - objects held from garbage collection by JVM for its purposes. GC Roots
  • 13. Desirable GC Features • Safe: live data must never be erroneously freed. • Comprehensive: garbage should not remain unclaimed for more than a small number of collection cycles. • Efficient: No long pauses during which the application is not running. • Limit fragmentation: Avoid memory fragmentation.
  • 14. GC Design Choices • Serial vs Parallel • Concurrent vs Stop-the-World • Compacting : moving all the live objects together and completely reclaiming the remaining memory. vs • Non-Compacting : releases the space utilized by garbage objects in-place vs • Copying : copies live objects to a different memory area.
  • 15. Key performance metrics • Throughput: % of total time not spent in garbage collection, considered over long periods of time. • Pauses: times when an application appears unresponsive because GC is occurring. • Frequency of collection: how often collection occurs, relative to application execution. • Promptness: time between when an object is dead and when memory is reclaimed. • Footprint: working set of a process, measured in pages and cache lines.
  • 16. • Generations: separate pools holding objects of different ages. • Weak Generational Hypothesis: – Most allocated objects die young. – Few references from older to younger objects exist. Generational Collection
  • 19. Young Generation Collection Empty Empty O2 O3 O5 O6 O7 O8 O9 O10 O5 O7 O10 Eden S1 S2 Empty Empty O2 O3 O6 O8 O9 Eden S1 S2 After Minor GC2
  • 20. Old (and Perm) Generation Collection • mark-sweep-compact collection algorithm. • Mark: the collector identifies which objects are still live. • Sweep: “sweeps” over the generations, identifying garbage. • Compact: The collector then performs sliding compaction, sliding the live objects towards the beginning of the old generation
  • 21. Comparing GC Strategies Pause Pause Concurrent Mark Re-Mark Serial Parallel Concurrent Application Thread GC Thread
  • 22. Parallel Collector • Minor GC: uses a parallel version of the minor GC algorithm utilized by the Serial Collector. – Reduced pause times. • Full GC: same as Serial Collector – (mark-sweep-compact) • can be explicitly requested by using - XX:+UseParallelGC command line option
  • 23. Parallel Compacting Collector • Minor GC: same algorithm as parallel collector. • Full GC: same as Serial Collector – (mark-sweep-compact) • can be explicitly requested by using - XX:+UseParallelGC command line option
  • 24. CMS Collector • Concurrent Mark and Sweep 1. Initial marking: GC root objects marked alive. Complete ‘Stop-the-World’. 2. Concurrent marking: marked root objects are traversed and all reachable objects are marked. Another round of marking of objects allocated during this phase! 3. Final marking: Stop-the-World and all remaining newly allocated objects are marked alive. 4. Sweep!
  • 26. Garbage First (G1) Collector • The heap is partitioned into a set of equal-sized heap regions, each a contiguous range of virtual memory • Concurrent marking phase to determine liveness of objects across the heap. • After the mark phase completes, G1 focuses on the regions that are likely to be full of garbage. • Copies objects to a single region on the heap, and in the process both compacts and frees up memory