SlideShare una empresa de Scribd logo
1 de 17
THE CHRONICLES OF GARBAGE COLLECTION
BY
Rupreet Singh Gujral (rupreetg@outlook.com)
Product Development / Architect / Entrepreneur
AGENDA
• Memory Concepts
• Basic Principles
• Advantages and Disadvantages of using GC
• GC Algorithm
• Setting the context
• CLR implementation of GC
• Best practices related to memory management in .NET
MEMORY CONCEPTS
• Physical Memory: This is the physical RAM on the machine/device. This is mainly used by kernel
drivers.
• Virtual Memory: It’s the memory emulation Operating System does for user to store and access data.
Its not related to physical memory. Virtual Memory is used at system level.
• Address space: This is specific to the memory allocated/used by a process. Threads in a process use
address space for their stack, etc. Address space is used at process level.
• Private bytes: Private Bytes is the current size, in bytes, of memory that this process has allocated
that cannot be shared with other processes.
• Working Set: The Working Set is the set of memory pages touched recently by the threads in the
process.
ARE YOU GUYS AWAKE?
• Suppose user is running an application on a x64 bit machine.
• The machine has 4GB RAM installed.
• Task Manager shows 2GB of total RAM is used and rest is free
• After running application, it throws “Out Of Memory” (OOM) exception.
How?
OK, LET ME HELP YOU!
• Application always allocate memory in its “address space”. If the
allocated “address space” is exhausted, only then you’ll get OOM
exception even if Virtual Memory is available
BASIC PRINCIPLES!
• Find objects that cannot be accessed in the future
• Reclaim/Release the resources used by those objects
HISTORY
Garbage collection was invented by John McCarthy around 1959 to
solve problems in Lisp
ADVANTAGES AND DISADVANTAGES
+ Automatic memory reclaim of objects that are not required
+ Memory Leaks are taken care of (almost!)
+ Bugs like dangling pointers, double free, etc
+ Free developer from manually taking care of memory mgmt.
- Performance Impact; consume resources
- Pauses in application
- Non deterministic, not real time
LETS SEE HOW MANY GARBAGE OBJECTS
WE CAN FIND?
GC ALGORITHM
• Reference Counting: Each object has a flag telling if it is referenced or not.
• Mark and Sweep: Two round collection cycle. First round it marks objects which are live
and in second round it clears the unused objects
• Copying Collectors: Create two heaps of same size. Use one for allocations; when
filled, pause the system and copy objects to other.
• Mark Compact Collector: Extended version of Mark and Sweep. In the second phase,
it compacts the heap to avoid fragmentation.
SETTING THE CONTEXT
• Reachability: GC depends on reachability heavily – to see if objects are reachable
or not.
• Roots: Starting point for GC to traverse the memory. Global & Static variables, etc
• Generations: Memory divided into generation. GC collects objects specific to
generation, avoiding full memory scan.
• Managed Heap: Process “continuous” address space which is governed by CLR/GC
• Determinism: GC are non-deterministic in the time of object finalization.
CLR IMPLEMENTATION OF GC
Object A
Object B
Object C
Managed Heap
NextObjPtr
Allocations
CLR IMPLEMENTATION OF GC
Image Source: MSDN
Allocated Objects in Heap
Managed Heap after Collection
Collection Algorithm
CLR IMPLEMENTATION OF GC
Image Source: MSDN
Finalization
Heap with multiple objects Managed Heap after Garbage Collection
CLR IMPLEMENTATION OF GC
Finalization Cont…
Managed Heap after Second Garbage Collection
# Objects with Finalize needs two GCs for cleanup.
Avoid having Finalize methods
# Finalize are different from destructor
# Any exception in Finalize should be handled and
return as if nothing happened. This helps other
Finalize method to execute
# Developers doesn’t control the execution (and the
order) of Finalize methods
# Finalizable objects should avoid referring to non-
Finalizable objects. Break the object into two types
and let the light weight have Finalize
BEST PRACTICES RELATED TO MEMORY
MANAGEMENT IN .NET
• Assigning NULL to an object when its not needed doesn’t collect the object instantly.
• While designing classes, if it has some unmanaged resources, do implement Dispose
Pattern and Finalize method
• In Dispose implementation, do call GC.SuppressFinalize method.
• If the class has Close/Dispose method, it’s the responsibility of the caller to call them.
Finalize methods are implemented here in case caller forgets to call them
• Avoid calling GC.Collect(..);
Q&A
Aim and shoot your questions!
Image source: http://egamer.co.za/2011/07/review-shadows-of-the-damned/
THANK YOU!
Image Source: http://www.comicvine.com/forums/battles-7/spiderman-vs-wesker-670859/

Más contenido relacionado

Destacado (6)

ORM Tools
ORM ToolsORM Tools
ORM Tools
 
iPhone Development
iPhone DevelopmentiPhone Development
iPhone Development
 
Umbraco CMS
Umbraco CMSUmbraco CMS
Umbraco CMS
 
Android app development
Android app developmentAndroid app development
Android app development
 
Node.js
Node.jsNode.js
Node.js
 
Twitter Bootstrap
Twitter BootstrapTwitter Bootstrap
Twitter Bootstrap
 

Similar a Chronicles Of Garbage Collection (GC)

Garbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMGarbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVM
jaganmohanreddyk
 
Memory Management in Go: Stack, Heap & Garbage Collector
Memory Management in Go: Stack, Heap & Garbage CollectorMemory Management in Go: Stack, Heap & Garbage Collector
Memory Management in Go: Stack, Heap & Garbage Collector
Wednesday Solutions
 

Similar a Chronicles Of Garbage Collection (GC) (20)

.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
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance Tuning
 
Managing Memory in Swift (Yes, that's a thing)
Managing Memory in Swift (Yes, that's a thing)Managing Memory in Swift (Yes, that's a thing)
Managing Memory in Swift (Yes, that's a thing)
 
Memory Management & Garbage Collection
Memory Management & Garbage CollectionMemory Management & Garbage Collection
Memory Management & Garbage Collection
 
Unity - Internals: memory and performance
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performance
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in Andoid
 
Garbage Collection in Java.pdf
Garbage Collection in Java.pdfGarbage Collection in Java.pdf
Garbage Collection in Java.pdf
 
Coding Best Practices For Memory Management
Coding Best Practices For Memory Management Coding Best Practices For Memory Management
Coding Best Practices For Memory Management
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Java at Scale, Dallas JUG, October 2013
Java at Scale, Dallas JUG, October 2013Java at Scale, Dallas JUG, October 2013
Java at Scale, Dallas JUG, October 2013
 
Garbage Collection .Net
Garbage Collection .NetGarbage Collection .Net
Garbage Collection .Net
 
garbage collector
garbage collectorgarbage collector
garbage collector
 
Garbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMGarbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVM
 
Effective memory management
Effective memory managementEffective memory management
Effective memory management
 
Effective memory management
Effective memory managementEffective memory management
Effective memory management
 
Low latency Java apps
Low latency Java appsLow latency Java apps
Low latency Java apps
 
Profiling tools and Android Performance patterns
Profiling tools and Android Performance patternsProfiling tools and Android Performance patterns
Profiling tools and Android Performance patterns
 
Memory Management in Go: Stack, Heap & Garbage Collector
Memory Management in Go: Stack, Heap & Garbage CollectorMemory Management in Go: Stack, Heap & Garbage Collector
Memory Management in Go: Stack, Heap & Garbage Collector
 
Optimization in Unity: simple tips for developing with "no surprises" / Anton...
Optimization in Unity: simple tips for developing with "no surprises" / Anton...Optimization in Unity: simple tips for developing with "no surprises" / Anton...
Optimization in Unity: simple tips for developing with "no surprises" / Anton...
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

Chronicles Of Garbage Collection (GC)

  • 1. THE CHRONICLES OF GARBAGE COLLECTION BY Rupreet Singh Gujral (rupreetg@outlook.com) Product Development / Architect / Entrepreneur
  • 2. AGENDA • Memory Concepts • Basic Principles • Advantages and Disadvantages of using GC • GC Algorithm • Setting the context • CLR implementation of GC • Best practices related to memory management in .NET
  • 3. MEMORY CONCEPTS • Physical Memory: This is the physical RAM on the machine/device. This is mainly used by kernel drivers. • Virtual Memory: It’s the memory emulation Operating System does for user to store and access data. Its not related to physical memory. Virtual Memory is used at system level. • Address space: This is specific to the memory allocated/used by a process. Threads in a process use address space for their stack, etc. Address space is used at process level. • Private bytes: Private Bytes is the current size, in bytes, of memory that this process has allocated that cannot be shared with other processes. • Working Set: The Working Set is the set of memory pages touched recently by the threads in the process.
  • 4. ARE YOU GUYS AWAKE? • Suppose user is running an application on a x64 bit machine. • The machine has 4GB RAM installed. • Task Manager shows 2GB of total RAM is used and rest is free • After running application, it throws “Out Of Memory” (OOM) exception. How?
  • 5. OK, LET ME HELP YOU! • Application always allocate memory in its “address space”. If the allocated “address space” is exhausted, only then you’ll get OOM exception even if Virtual Memory is available
  • 6. BASIC PRINCIPLES! • Find objects that cannot be accessed in the future • Reclaim/Release the resources used by those objects HISTORY Garbage collection was invented by John McCarthy around 1959 to solve problems in Lisp
  • 7. ADVANTAGES AND DISADVANTAGES + Automatic memory reclaim of objects that are not required + Memory Leaks are taken care of (almost!) + Bugs like dangling pointers, double free, etc + Free developer from manually taking care of memory mgmt. - Performance Impact; consume resources - Pauses in application - Non deterministic, not real time
  • 8. LETS SEE HOW MANY GARBAGE OBJECTS WE CAN FIND?
  • 9. GC ALGORITHM • Reference Counting: Each object has a flag telling if it is referenced or not. • Mark and Sweep: Two round collection cycle. First round it marks objects which are live and in second round it clears the unused objects • Copying Collectors: Create two heaps of same size. Use one for allocations; when filled, pause the system and copy objects to other. • Mark Compact Collector: Extended version of Mark and Sweep. In the second phase, it compacts the heap to avoid fragmentation.
  • 10. SETTING THE CONTEXT • Reachability: GC depends on reachability heavily – to see if objects are reachable or not. • Roots: Starting point for GC to traverse the memory. Global & Static variables, etc • Generations: Memory divided into generation. GC collects objects specific to generation, avoiding full memory scan. • Managed Heap: Process “continuous” address space which is governed by CLR/GC • Determinism: GC are non-deterministic in the time of object finalization.
  • 11. CLR IMPLEMENTATION OF GC Object A Object B Object C Managed Heap NextObjPtr Allocations
  • 12. CLR IMPLEMENTATION OF GC Image Source: MSDN Allocated Objects in Heap Managed Heap after Collection Collection Algorithm
  • 13. CLR IMPLEMENTATION OF GC Image Source: MSDN Finalization Heap with multiple objects Managed Heap after Garbage Collection
  • 14. CLR IMPLEMENTATION OF GC Finalization Cont… Managed Heap after Second Garbage Collection # Objects with Finalize needs two GCs for cleanup. Avoid having Finalize methods # Finalize are different from destructor # Any exception in Finalize should be handled and return as if nothing happened. This helps other Finalize method to execute # Developers doesn’t control the execution (and the order) of Finalize methods # Finalizable objects should avoid referring to non- Finalizable objects. Break the object into two types and let the light weight have Finalize
  • 15. BEST PRACTICES RELATED TO MEMORY MANAGEMENT IN .NET • Assigning NULL to an object when its not needed doesn’t collect the object instantly. • While designing classes, if it has some unmanaged resources, do implement Dispose Pattern and Finalize method • In Dispose implementation, do call GC.SuppressFinalize method. • If the class has Close/Dispose method, it’s the responsibility of the caller to call them. Finalize methods are implemented here in case caller forgets to call them • Avoid calling GC.Collect(..);
  • 16. Q&A Aim and shoot your questions! Image source: http://egamer.co.za/2011/07/review-shadows-of-the-damned/
  • 17. THANK YOU! Image Source: http://www.comicvine.com/forums/battles-7/spiderman-vs-wesker-670859/