SlideShare a Scribd company logo
1 of 36
CLR: Garbage Collection Inside Out
Maoni Stephens
FUN421
Software Design Engineer
Microsoft Corporation
Agenda
Basics
Generations
Segments
Allocation
Collection
Large Object Heap
Different Flavors of GC
Pinning
Tools and Resources
Generation 1 Generation 0
New Heap Begins with New Generation
Accessible References Keep Objects Alive
Compacts Referenced Objects
Objects Promoted to Older Generation
New Allocations Rebuild New Generation
Basics
Agenda
Basics
Generations
Segments
Allocation
Collection
Large Object Heap
Different Flavors of GC
Pinning
Tools and Resources
Generational GC
Three generations
Most objects die in gen0
Gen1 holds in the in flight data
Gen2 holds the long lived data
Large object heap
Gen0 and Gen1 – ephemeral generations
Agenda
Basics
Generations
Segments
Allocation
Collection
Large Object Heap
Different Flavors of GC
Pinning
Tools and Resources
GC Heap Segments
Unit of VirtualAlloc
When CLR is loaded, initial segments are
allocated
Additional segments reserved as needed
Committed/Decommitted as needed in the
segment
Deleted when not in use
VM hoarding feature in next CLR 1.1 SP
and CLR 2.0 –
STARTUP_HOARD_GC_VM startup flag
Generations And Segments
Start from the ephemeral segment
Ephemeral segment becomes a gen2
segment
Newly reserved segment becomes
ephemeral
Many gen2 segments, only one ephemeral
Before GC #1
Gen1 Gen0
Before GC #500
Gen2
Gen2
Gen2 Gen1 Gen0
Gen0
Before GC #0
Before GC #2
Gen2 Gen1 Gen0
Before GC #100
Gen2
Gen2 Gen1 Gen0
Agenda
Basics
Generations
Segments
Allocation
Collection
Large Object Heap
Different Flavors of GC
Pinning
Tools and Resources
Allocation
Cheap lock on UP; lock free on MP
Moving a pointer forward
Clearing the memory for new objects
Register for finalization if applicable
Objects allocated together are
close together
Agenda
Basics
Generations
Segments
Allocation
Collection
Large Object Heap
Different Flavors of GC
Pinning
Tools and Resources
Collection
When
Allocation. Not enough space in
gen0.
Induced GC. By calling
System.GC.Collect().
System pressure.
Collection
How
Suspend managed threads
GC
Resume managed threads
Two phases of GC
Mark
Compact
Roots
Stack
Handle table
Statics
Older generation(s)
Finalizer queue
Agenda
Basics
Generations
Segments
Allocation
Collection
Large Object Heap
Different Flavors of GC
Pinning
Tools and Resources
Large Object Heap
For objects that are 85,000 bytes or larger
Compacting large objects costs a lot
So we only sweep (freelist)
Many LOH segments
Segments are handled similarly to small
object heap segments
Collection happens during gen2 GCs
Collection – Cost
GC takes time – “% time in GC” counter
If objects die in gen0 (survival rate is 0) it’s
the ideal situation
The longer the object lives before being
dead, the worse (with exceptions)
Gen0 and gen1 GCs should both be
relatively cheap; gen2 GCs could cost a lot
LOH – different cost model
Temporary large objects could be bad
Should reuse if possible
Agenda
Basics
Generations
Segments
Allocation
Collection
Large Object Heap
Different Flavors of GC
Pinning
Tools and Resources
Concurrent GC
Why do we have concurrent GC
For interactive applications
How it’s done
Trade some CPU and memory for shorter
pause time
Only for gen2
Done on a concurrent GC thread
How do you get concurrent GC
On by default
Can be turned off via hosting or config
Server GC
Why do we have server GC – for server apps
that
Have a fairly consistent number of requests
Require high scalibility and high throughput
How it’s done
One thread for each CPU, running at highest priority
One ephemeral segment per CPU
How do you get server GC
Only on via config or hosting
Hosts like ASP.NET and SQLCLR use server GC
In CLR 1.1 it’s in mscorsvr.dll; in CLR 2.0 it’s in
mscorwks.dll
WKS GC SVR GC
Where it runs On the user thread
that triggered GC
On the GC threads
running at highest
priority
On a multi proc
machine
One small object
heap + One LOH
N small object
heaps + N LOHs
On a uni proc
machine
WKS GC +
concurrent GC (if
not turned off)
WKS GC +
concurrent GC
OFF
Agenda
Basics
Generations
Segments
Allocation
Collection
Large Object Heap
Different Flavors of GC
Pinning
Tools and Resources
Pinning
Why do we need pinning
Interop with unmanaged code
How objects get pinned
Use of GCHandle of type
GCHandleType.Pinned
Allowed by language syntax, eg. fixed in c#
Args get pinned by the interop frame
Fragmentation problem
After N more GCs
Gen1 P P
After GC X
Gen2 P P
Gen1 start
Before GC X
Gen1
Gen0 start
P P
Gen0 start
Gen2 P P
Fragmentation Problem Caused By Pinning
Gen0 start
Gen1 start
Without demotion
Gen0 start
Gen2
Gen1 start
P P
With demotion
Gen0 start
Gen2
Gen1 start
P P
Before GC After GC
Gen2
Seg0
Seg1
Gen2
Seg2
Gen2
Seg3
Gen2
Gen1
Eph P Gen0 P
Without Segment Reuse
Gen2
Seg0
Seg1
Gen2
Seg2
Gen2
Seg3
Gen2
Old Eph Gen2 P P
Gen1
New Eph
Before GC After GC
Gen2
Seg0
Seg1
Gen2
Seg2
Gen2
Seg3
Gen2
Gen1
Eph P Gen0 P
With Segment Reuse
Gen2
Seg0
Seg1
Gen2
Seg2
Gen2
Gen2 P P
Old Eph
Old Seg3,
New Eph
Gen2 Gen1
What The User Code Can Do
To Help
Best patterns
Pinning for a short time is cheap.
Create pinned buffers at the beginning that will stay in
regions that are very compacted
Create pinned buffers that stay together instead of
scattered around
Techniques
Allocate a pinned big buffer (byte array on the LOH),
give out a chunk at a time
Allocate a pool of small buffers and hand one out
when needed
void M(byte[] b)
{
// if the buffer is already in gen2 it’s unlikely to move.
if(GC.GetGeneration(b) ==
GC.MaxGeneration ||
// avoid copying if the buffer is too big
b.Length > 8 * 1024)
{
RealM(b);
}
// GetBuffer will allocate one if none is free.
byte[] TempBuffer = Pool.GetBuffer();
RealM(TempBuffer);
CopyBackToUserBuffer(TempBuffer, b);
Pool.Release(TempBuffer);
}
Managed Caches
Design patterns
Don’t do it in the finalizer
Use combination of weak and strong references –
could convert strong to weak after certain period
Cache tuning
Hit rate
Cost to add an item
Cost to find an item
Frequency of cleanup
If not implemented carefully could easily cause more
gen2 collections than needed
// sweep the cache for dead objects and compacts the list.
static void sweep_WeakRef()
{
// don't bother if no new collection happened since
// we swept last
if (GC.CollectionCount(0) != gen0_count)
gen0_count = GC.CollectionCount (0);
else
return;
lock (list) {
for (int i = 0; i < WeakRef_fill;) {
if (list[i].Target == null) {
// install the last element in the free slot.
WeakRef_fill--;
if (i != WeakRef_fill) {
list[i] = list[WeakRef_fill];
list[WeakRef_fill] = null;
}
}
else
i++;
}
}
}
Why We Don’t Allow Many
Customized Settings
Only allow very few settings specified via
hosting API or config
Advantages for GC to do the tuning for you
GC has intimate knowledge of memory when
applications run
GC is tested on many platforms + many
configurations
Looking Ahead
Challenges on 64-bit
More common as people start using 64-bit
machines
VM is practically unlimited so physical
memory is the limit
Servers like the SQL Server tend to not
allow paging
Gen2 could take a long time
Tools And Resources
http://blogs.msdn.com/maoni/
CLRProfiler
.NET CLR Memory performance counters
The SoS Debugger Extension for
windbg/cdb
vadump
Task Manager
© 2005 Microsoft Corporation. All rights reserved.
This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

More Related Content

What's hot (20)

초보자를 위한 Git & GitHub
초보자를 위한 Git & GitHub초보자를 위한 Git & GitHub
초보자를 위한 Git & GitHub
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Intro to Git and GitHub
Intro to Git and GitHubIntro to Git and GitHub
Intro to Git and GitHub
 
GitLab
GitLabGitLab
GitLab
 
Git-flow workflow and pull-requests
Git-flow workflow and pull-requestsGit-flow workflow and pull-requests
Git-flow workflow and pull-requests
 
Git & GitLab
Git & GitLabGit & GitLab
Git & GitLab
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
 
GIT INTRODUCTION
GIT INTRODUCTIONGIT INTRODUCTION
GIT INTRODUCTION
 
Git in 10 minutes
Git in 10 minutesGit in 10 minutes
Git in 10 minutes
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programming
 
Git basic
Git basicGit basic
Git basic
 
GitLab for CI/CD process
GitLab for CI/CD processGitLab for CI/CD process
GitLab for CI/CD process
 
Jenkins_1679702972.pdf
Jenkins_1679702972.pdfJenkins_1679702972.pdf
Jenkins_1679702972.pdf
 
Git
GitGit
Git
 
Monorepo at Pinterest
Monorepo at PinterestMonorepo at Pinterest
Monorepo at Pinterest
 
The Fundamentals of Git
The Fundamentals of GitThe Fundamentals of Git
The Fundamentals of Git
 
Git hooks
Git hooksGit hooks
Git hooks
 
Git
GitGit
Git
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
 
Managing dependencies with gradle
Managing dependencies with gradleManaging dependencies with gradle
Managing dependencies with gradle
 

Similar to Fun421 stephens

Low pause GC in HotSpot
Low pause GC in HotSpotLow pause GC in HotSpot
Low pause GC in HotSpotjClarity
 
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...Maarten Balliauw
 
Let's talk about Garbage Collection
Let's talk about Garbage CollectionLet's talk about Garbage Collection
Let's talk about Garbage CollectionHaim Yadid
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionMudit Gupta
 
Garbage First and you
Garbage First and youGarbage First and you
Garbage First and youKai Koenig
 
Garbage First and You!
Garbage First and You!Garbage First and You!
Garbage First and You!devObjective
 
Garbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMGarbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMjaganmohanreddyk
 
Performance tuning jvm
Performance tuning jvmPerformance tuning jvm
Performance tuning jvmPrem Kuppumani
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionHaribabu Nandyal Padmanaban
 
Scaling an ELK stack at bol.com
Scaling an ELK stack at bol.comScaling an ELK stack at bol.com
Scaling an ELK stack at bol.comRenzo Tomà
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...Maarten Balliauw
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Maarten Balliauw
 
Java 7 - New Features - by Mihail Stoynov and Svetlin Nakov
Java 7 - New Features - by Mihail Stoynov and Svetlin NakovJava 7 - New Features - by Mihail Stoynov and Svetlin Nakov
Java 7 - New Features - by Mihail Stoynov and Svetlin NakovSvetlin Nakov
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance TuningJeremy Leisy
 
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...Maarten Balliauw
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarMaarten Balliauw
 
ConFoo - Exploring .NET’s memory management – a trip down memory lane
ConFoo - Exploring .NET’s memory management – a trip down memory laneConFoo - Exploring .NET’s memory management – a trip down memory lane
ConFoo - Exploring .NET’s memory management – a trip down memory laneMaarten Balliauw
 

Similar to Fun421 stephens (20)

Low pause GC in HotSpot
Low pause GC in HotSpotLow pause GC in HotSpot
Low pause GC in HotSpot
 
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
Exploring .NET memory management - A trip down memory lane - Copenhagen .NET ...
 
Let's talk about Garbage Collection
Let's talk about Garbage CollectionLet's talk about Garbage Collection
Let's talk about Garbage Collection
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
JVM Magic
JVM MagicJVM Magic
JVM Magic
 
Garbage First and you
Garbage First and youGarbage First and you
Garbage First and you
 
Garbage First and You!
Garbage First and You!Garbage First and You!
Garbage First and You!
 
Garbage First & You
Garbage First & YouGarbage First & You
Garbage First & You
 
Garbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMGarbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVM
 
Performance tuning jvm
Performance tuning jvmPerformance tuning jvm
Performance tuning jvm
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage Collection
 
ZGC-SnowOne.pdf
ZGC-SnowOne.pdfZGC-SnowOne.pdf
ZGC-SnowOne.pdf
 
Scaling an ELK stack at bol.com
Scaling an ELK stack at bol.comScaling an ELK stack at bol.com
Scaling an ELK stack at bol.com
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)
 
Java 7 - New Features - by Mihail Stoynov and Svetlin Nakov
Java 7 - New Features - by Mihail Stoynov and Svetlin NakovJava 7 - New Features - by Mihail Stoynov and Svetlin Nakov
Java 7 - New Features - by Mihail Stoynov and Svetlin Nakov
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance Tuning
 
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinar
 
ConFoo - Exploring .NET’s memory management – a trip down memory lane
ConFoo - Exploring .NET’s memory management – a trip down memory laneConFoo - Exploring .NET’s memory management – a trip down memory lane
ConFoo - Exploring .NET’s memory management – a trip down memory lane
 

More from Tess Ferrandez

funwithalgorithms.pptx
funwithalgorithms.pptxfunwithalgorithms.pptx
funwithalgorithms.pptxTess Ferrandez
 
CSI .net core - debugging .net applications
CSI .net core - debugging .net applicationsCSI .net core - debugging .net applications
CSI .net core - debugging .net applicationsTess Ferrandez
 
Debugging performance issues, memory issues and crashes in .net applications rev
Debugging performance issues, memory issues and crashes in .net applications revDebugging performance issues, memory issues and crashes in .net applications rev
Debugging performance issues, memory issues and crashes in .net applications revTess Ferrandez
 
Common asp.net production issues rev
Common asp.net production issues revCommon asp.net production issues rev
Common asp.net production issues revTess Ferrandez
 
Facenet - Paper Review
Facenet - Paper ReviewFacenet - Paper Review
Facenet - Paper ReviewTess Ferrandez
 
AI and Ethics - We are the guardians of our future
AI and Ethics - We are the guardians of our futureAI and Ethics - We are the guardians of our future
AI and Ethics - We are the guardians of our futureTess Ferrandez
 
Deep learning and computer vision
Deep learning and computer visionDeep learning and computer vision
Deep learning and computer visionTess Ferrandez
 
A practical guide to deep learning
A practical guide to deep learningA practical guide to deep learning
A practical guide to deep learningTess Ferrandez
 
Notes from Coursera Deep Learning courses by Andrew Ng
Notes from Coursera Deep Learning courses by Andrew NgNotes from Coursera Deep Learning courses by Andrew Ng
Notes from Coursera Deep Learning courses by Andrew NgTess Ferrandez
 
A developers guide to machine learning
A developers guide to machine learningA developers guide to machine learning
A developers guide to machine learningTess Ferrandez
 
My bot has a personality disorder
My bot has a personality disorderMy bot has a personality disorder
My bot has a personality disorderTess Ferrandez
 

More from Tess Ferrandez (15)

funwithalgorithms.pptx
funwithalgorithms.pptxfunwithalgorithms.pptx
funwithalgorithms.pptx
 
Debugging .NET apps
Debugging .NET appsDebugging .NET apps
Debugging .NET apps
 
CSI .net core - debugging .net applications
CSI .net core - debugging .net applicationsCSI .net core - debugging .net applications
CSI .net core - debugging .net applications
 
Debugging performance issues, memory issues and crashes in .net applications rev
Debugging performance issues, memory issues and crashes in .net applications revDebugging performance issues, memory issues and crashes in .net applications rev
Debugging performance issues, memory issues and crashes in .net applications rev
 
Common asp.net production issues rev
Common asp.net production issues revCommon asp.net production issues rev
Common asp.net production issues rev
 
Perf by design
Perf by designPerf by design
Perf by design
 
C# to python
C# to pythonC# to python
C# to python
 
Facenet - Paper Review
Facenet - Paper ReviewFacenet - Paper Review
Facenet - Paper Review
 
AI and Ethics - We are the guardians of our future
AI and Ethics - We are the guardians of our futureAI and Ethics - We are the guardians of our future
AI and Ethics - We are the guardians of our future
 
Deep learning and computer vision
Deep learning and computer visionDeep learning and computer vision
Deep learning and computer vision
 
A practical guide to deep learning
A practical guide to deep learningA practical guide to deep learning
A practical guide to deep learning
 
Notes from Coursera Deep Learning courses by Andrew Ng
Notes from Coursera Deep Learning courses by Andrew NgNotes from Coursera Deep Learning courses by Andrew Ng
Notes from Coursera Deep Learning courses by Andrew Ng
 
A developers guide to machine learning
A developers guide to machine learningA developers guide to machine learning
A developers guide to machine learning
 
My bot has a personality disorder
My bot has a personality disorderMy bot has a personality disorder
My bot has a personality disorder
 
.Net debugging 2017
.Net debugging   2017.Net debugging   2017
.Net debugging 2017
 

Recently uploaded

Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
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
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 

Recently uploaded (20)

Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
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...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 

Fun421 stephens

  • 1. CLR: Garbage Collection Inside Out Maoni Stephens FUN421 Software Design Engineer Microsoft Corporation
  • 3. Generation 1 Generation 0 New Heap Begins with New Generation Accessible References Keep Objects Alive Compacts Referenced Objects Objects Promoted to Older Generation New Allocations Rebuild New Generation Basics
  • 5. Generational GC Three generations Most objects die in gen0 Gen1 holds in the in flight data Gen2 holds the long lived data Large object heap Gen0 and Gen1 – ephemeral generations
  • 7. GC Heap Segments Unit of VirtualAlloc When CLR is loaded, initial segments are allocated Additional segments reserved as needed Committed/Decommitted as needed in the segment Deleted when not in use VM hoarding feature in next CLR 1.1 SP and CLR 2.0 – STARTUP_HOARD_GC_VM startup flag
  • 8. Generations And Segments Start from the ephemeral segment Ephemeral segment becomes a gen2 segment Newly reserved segment becomes ephemeral Many gen2 segments, only one ephemeral
  • 9. Before GC #1 Gen1 Gen0 Before GC #500 Gen2 Gen2 Gen2 Gen1 Gen0 Gen0 Before GC #0 Before GC #2 Gen2 Gen1 Gen0 Before GC #100 Gen2 Gen2 Gen1 Gen0
  • 11. Allocation Cheap lock on UP; lock free on MP Moving a pointer forward Clearing the memory for new objects Register for finalization if applicable Objects allocated together are close together
  • 13. Collection When Allocation. Not enough space in gen0. Induced GC. By calling System.GC.Collect(). System pressure.
  • 14. Collection How Suspend managed threads GC Resume managed threads Two phases of GC Mark Compact
  • 17. Large Object Heap For objects that are 85,000 bytes or larger Compacting large objects costs a lot So we only sweep (freelist) Many LOH segments Segments are handled similarly to small object heap segments Collection happens during gen2 GCs
  • 18. Collection – Cost GC takes time – “% time in GC” counter If objects die in gen0 (survival rate is 0) it’s the ideal situation The longer the object lives before being dead, the worse (with exceptions) Gen0 and gen1 GCs should both be relatively cheap; gen2 GCs could cost a lot LOH – different cost model Temporary large objects could be bad Should reuse if possible
  • 20. Concurrent GC Why do we have concurrent GC For interactive applications How it’s done Trade some CPU and memory for shorter pause time Only for gen2 Done on a concurrent GC thread How do you get concurrent GC On by default Can be turned off via hosting or config
  • 21. Server GC Why do we have server GC – for server apps that Have a fairly consistent number of requests Require high scalibility and high throughput How it’s done One thread for each CPU, running at highest priority One ephemeral segment per CPU How do you get server GC Only on via config or hosting Hosts like ASP.NET and SQLCLR use server GC In CLR 1.1 it’s in mscorsvr.dll; in CLR 2.0 it’s in mscorwks.dll
  • 22. WKS GC SVR GC Where it runs On the user thread that triggered GC On the GC threads running at highest priority On a multi proc machine One small object heap + One LOH N small object heaps + N LOHs On a uni proc machine WKS GC + concurrent GC (if not turned off) WKS GC + concurrent GC OFF
  • 24. Pinning Why do we need pinning Interop with unmanaged code How objects get pinned Use of GCHandle of type GCHandleType.Pinned Allowed by language syntax, eg. fixed in c# Args get pinned by the interop frame Fragmentation problem
  • 25. After N more GCs Gen1 P P After GC X Gen2 P P Gen1 start Before GC X Gen1 Gen0 start P P Gen0 start Gen2 P P Fragmentation Problem Caused By Pinning Gen0 start Gen1 start
  • 26. Without demotion Gen0 start Gen2 Gen1 start P P With demotion Gen0 start Gen2 Gen1 start P P
  • 27. Before GC After GC Gen2 Seg0 Seg1 Gen2 Seg2 Gen2 Seg3 Gen2 Gen1 Eph P Gen0 P Without Segment Reuse Gen2 Seg0 Seg1 Gen2 Seg2 Gen2 Seg3 Gen2 Old Eph Gen2 P P Gen1 New Eph
  • 28. Before GC After GC Gen2 Seg0 Seg1 Gen2 Seg2 Gen2 Seg3 Gen2 Gen1 Eph P Gen0 P With Segment Reuse Gen2 Seg0 Seg1 Gen2 Seg2 Gen2 Gen2 P P Old Eph Old Seg3, New Eph Gen2 Gen1
  • 29. What The User Code Can Do To Help Best patterns Pinning for a short time is cheap. Create pinned buffers at the beginning that will stay in regions that are very compacted Create pinned buffers that stay together instead of scattered around Techniques Allocate a pinned big buffer (byte array on the LOH), give out a chunk at a time Allocate a pool of small buffers and hand one out when needed
  • 30. void M(byte[] b) { // if the buffer is already in gen2 it’s unlikely to move. if(GC.GetGeneration(b) == GC.MaxGeneration || // avoid copying if the buffer is too big b.Length > 8 * 1024) { RealM(b); } // GetBuffer will allocate one if none is free. byte[] TempBuffer = Pool.GetBuffer(); RealM(TempBuffer); CopyBackToUserBuffer(TempBuffer, b); Pool.Release(TempBuffer); }
  • 31. Managed Caches Design patterns Don’t do it in the finalizer Use combination of weak and strong references – could convert strong to weak after certain period Cache tuning Hit rate Cost to add an item Cost to find an item Frequency of cleanup If not implemented carefully could easily cause more gen2 collections than needed
  • 32. // sweep the cache for dead objects and compacts the list. static void sweep_WeakRef() { // don't bother if no new collection happened since // we swept last if (GC.CollectionCount(0) != gen0_count) gen0_count = GC.CollectionCount (0); else return; lock (list) { for (int i = 0; i < WeakRef_fill;) { if (list[i].Target == null) { // install the last element in the free slot. WeakRef_fill--; if (i != WeakRef_fill) { list[i] = list[WeakRef_fill]; list[WeakRef_fill] = null; } } else i++; } } }
  • 33. Why We Don’t Allow Many Customized Settings Only allow very few settings specified via hosting API or config Advantages for GC to do the tuning for you GC has intimate knowledge of memory when applications run GC is tested on many platforms + many configurations
  • 34. Looking Ahead Challenges on 64-bit More common as people start using 64-bit machines VM is practically unlimited so physical memory is the limit Servers like the SQL Server tend to not allow paging Gen2 could take a long time
  • 35. Tools And Resources http://blogs.msdn.com/maoni/ CLRProfiler .NET CLR Memory performance counters The SoS Debugger Extension for windbg/cdb vadump Task Manager
  • 36. © 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.