SlideShare a Scribd company logo
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!

More Related Content

What's hot (20)

PPTX
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
AWSKRUG - AWS한국사용자모임
 
PPTX
2022年ASP.NETCore2.2~6.0の旅.pptx
Masanori Masui
 
PDF
CloudWatch 성능 모니터링과 신속한 대응을 위한 노하우 - 박선용 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
Amazon Web Services Korea
 
PPT
10월 웨비나 - AWS에서 Active Directory 구축 및 연동 옵션 살펴보기 (김용우 솔루션즈 아키텍트)
Amazon Web Services Korea
 
PDF
日本のお客様におけるAmazon Auroraへの移行・検証事例と技術ポイント
Amazon Web Services Japan
 
PDF
AWS Black Belt Techシリーズ Amazon Kinesis
Amazon Web Services Japan
 
PDF
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
SeungYong Oh
 
PDF
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
Amazon Web Services Korea
 
PDF
Day 1 with Amazon Web Services - AWSご利用開始時に最低限おさえておきたい10のこと
Amazon Web Services Japan
 
PDF
AWS Black Belt Online Seminar 2017 Amazon Kinesis
Amazon Web Services Japan
 
PPT
Spring3.1概要 データアクセスとトランザクション処理
土岐 孝平
 
PDF
はじめよう DynamoDB ハンズオン
Amazon Web Services Japan
 
PDF
Amazon Personalize Event Tracker 실시간 고객 반응을 고려한 추천::김태수, 솔루션즈 아키텍트, AWS::AWS ...
Amazon Web Services Korea
 
PDF
AWS Lake Formation을 통한 손쉬운 데이터 레이크 구성 및 관리 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon Web Services Korea
 
PDF
20190828 AWS Black Belt Online Seminar Amazon Aurora with PostgreSQL Compatib...
Amazon Web Services Japan
 
PDF
KB국민은행은 시작했다 -  쉽고 빠른 클라우드 거버넌스 적용 전략 - 강병억 AWS 솔루션즈 아키텍트 / 장강홍 클라우드플랫폼단 차장, ...
Amazon Web Services Korea
 
PPTX
DeNA の AWS アカウント管理とセキュリティ監査自動化
DeNA
 
PDF
[Cloud OnAir] BigQuery の仕組みからベストプラクティスまでのご紹介 2018年9月6日 放送
Google Cloud Platform - Japan
 
PDF
Amazon Kinesis Analytics によるストリーミングデータのリアルタイム分析
Amazon Web Services Japan
 
PDF
Lambda EdgeとALB認証を導入した話
淳 千葉
 
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
AWSKRUG - AWS한국사용자모임
 
2022年ASP.NETCore2.2~6.0の旅.pptx
Masanori Masui
 
CloudWatch 성능 모니터링과 신속한 대응을 위한 노하우 - 박선용 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
Amazon Web Services Korea
 
10월 웨비나 - AWS에서 Active Directory 구축 및 연동 옵션 살펴보기 (김용우 솔루션즈 아키텍트)
Amazon Web Services Korea
 
日本のお客様におけるAmazon Auroraへの移行・検証事例と技術ポイント
Amazon Web Services Japan
 
AWS Black Belt Techシリーズ Amazon Kinesis
Amazon Web Services Japan
 
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
SeungYong Oh
 
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
Amazon Web Services Korea
 
Day 1 with Amazon Web Services - AWSご利用開始時に最低限おさえておきたい10のこと
Amazon Web Services Japan
 
AWS Black Belt Online Seminar 2017 Amazon Kinesis
Amazon Web Services Japan
 
Spring3.1概要 データアクセスとトランザクション処理
土岐 孝平
 
はじめよう DynamoDB ハンズオン
Amazon Web Services Japan
 
Amazon Personalize Event Tracker 실시간 고객 반응을 고려한 추천::김태수, 솔루션즈 아키텍트, AWS::AWS ...
Amazon Web Services Korea
 
AWS Lake Formation을 통한 손쉬운 데이터 레이크 구성 및 관리 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon Web Services Korea
 
20190828 AWS Black Belt Online Seminar Amazon Aurora with PostgreSQL Compatib...
Amazon Web Services Japan
 
KB국민은행은 시작했다 -  쉽고 빠른 클라우드 거버넌스 적용 전략 - 강병억 AWS 솔루션즈 아키텍트 / 장강홍 클라우드플랫폼단 차장, ...
Amazon Web Services Korea
 
DeNA の AWS アカウント管理とセキュリティ監査自動化
DeNA
 
[Cloud OnAir] BigQuery の仕組みからベストプラクティスまでのご紹介 2018年9月6日 放送
Google Cloud Platform - Japan
 
Amazon Kinesis Analytics によるストリーミングデータのリアルタイム分析
Amazon Web Services Japan
 
Lambda EdgeとALB認証を導入した話
淳 千葉
 

Viewers also liked (20)

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

Similar to An Introduction to JVM Internals and Garbage Collection in Java (20)

PPTX
Jvm lecture
sdslnmd
 
ODP
Quick introduction to Java Garbage Collector (JVM GC)
Marcos García
 
PDF
Performance Tuning - Understanding Garbage Collection
Haribabu Nandyal Padmanaban
 
PDF
Let's talk about Garbage Collection
Haim Yadid
 
PPTX
Exploring Java Heap Dumps (Oracle Code One 2018)
Ryan Cuprak
 
ODP
Garbage Collection in Hotspot JVM
jaganmohanreddyk
 
PPT
«Большие объёмы данных и сборка мусора в Java
Olga Lavrentieva
 
PPTX
Pune-Cocoa: Blocks and GCD
Prashant Rane
 
PPTX
G1 collector and tuning and Cassandra
Chris Lohfink
 
PDF
.NET Core, ASP.NET Core Course, Session 4
Amin Mesbahi
 
PPTX
What’s expected in Java 9
Gal Marder
 
PPTX
Javasession10
Rajeev Kumar
 
KEY
Everything I Ever Learned About JVM Performance Tuning @Twitter
Attila Szegedi
 
PDF
Profiler Guided Java Performance Tuning
osa_ora
 
PPTX
Java performance monitoring
Simon Ritter
 
PPTX
OpenJDK Concurrent Collectors
Monica Beckwith
 
PDF
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
ketan_patel25
 
PPT
Java programing considering performance
Roger Xia
 
PPTX
.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup
 
PDF
Memory Analysis of the Dalvik (Android) Virtual Machine
Andrew Case
 
Jvm lecture
sdslnmd
 
Quick introduction to Java Garbage Collector (JVM GC)
Marcos García
 
Performance Tuning - Understanding Garbage Collection
Haribabu Nandyal Padmanaban
 
Let's talk about Garbage Collection
Haim Yadid
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Ryan Cuprak
 
Garbage Collection in Hotspot JVM
jaganmohanreddyk
 
«Большие объёмы данных и сборка мусора в Java
Olga Lavrentieva
 
Pune-Cocoa: Blocks and GCD
Prashant Rane
 
G1 collector and tuning and Cassandra
Chris Lohfink
 
.NET Core, ASP.NET Core Course, Session 4
Amin Mesbahi
 
What’s expected in Java 9
Gal Marder
 
Javasession10
Rajeev Kumar
 
Everything I Ever Learned About JVM Performance Tuning @Twitter
Attila Szegedi
 
Profiler Guided Java Performance Tuning
osa_ora
 
Java performance monitoring
Simon Ritter
 
OpenJDK Concurrent Collectors
Monica Beckwith
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
ketan_patel25
 
Java programing considering performance
Roger Xia
 
.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup
 
Memory Analysis of the Dalvik (Android) Virtual Machine
Andrew Case
 
Ad

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 

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