SlideShare una empresa de Scribd logo
1 de 50
GC & Memory leak Author : Toan Vo
Overview What is garbage collector (GC)? GC algorithm. Generation. Type of Garbage collector GC in .Net framework 4  Improve performance Common memory leak in WPF or Silverlight Detect memory leak.
What is Garbage collector Automatic garbage collection is a process by which the system will automatically take care of the memory used by unwanted objects (we call them as garbage) to be released Garbage collection is a process of releasing the memory used by the objects, which are no longer referenced.
What is Garbage collector Garbage collector as a separate thread. This thread will be running always at the back end.  Lowest priority. When GC already called?  When system finds there is no space in the managed heap (managed heap is nothing but a bunch of memory allocated for the program at run time). GC thread will be given REALTIME priority (REALTIME priority is the highest priority in Windows) and collect all the un wanted objects.
GC Benefits ,[object Object]
No longer have to implement any code that. Manages the lifetime of any resources.
It is not possible to leak resources.
It is not possible to access a resource that is freed.,[object Object]
GC Algorithm Check from roots Build a graph objects If roots added new objects. Then add object into graph. Continue with another roots.  If root added another object already in map then move to next root.
GC Algorithm The garbage collector now walks through the heap linearly. The garbage collector then shifts the non-garbage objects down in memory removing all of the gaps in the heap.
GC Algorithm
GC Algorithm GC Start examining all the objects in the level Generation Zero. If it finds any object marked for garbage collection, it will simply remove those objects from the memory. GC to compact the memory structure after collecting the objects GC will look which are all the objects survive after the sweep (collection). Those objects will be moved to Generation One and now the Generation Zero is empty for filling new objects. Happen with Generation One same as Generation Zero as well.
GC Algorithm What’s happen when Gen 1 filled? Expand size of gen 2 when if it can Move all of objects still alive at Gen 1 to Gen 2 Note: If object has size 85,000 bytes or greater will start off in Generation 2 directly. Only generation 2 is allow to grow as needed.
GC Algorithm Generation 0 (Gen 0). This consists of newly created objects. Gen 0 is collected frequently to ensure that short-lived objects are quickly cleaned up. Those objects that survive a Gen 0 collection are promoted to Generation 1. Generation 1 (Gen 1). This is collected less frequently than Gen 0 and contains longer-lived objects that were promoted from Gen 0. Generation 2 (Gen 2). This contains objects promoted from Gen 1 (which means it contains the longest-lived objects) and is collected even less frequently. The general strategy of the garbage collector is to collect and move longer-lived objects less frequently.
GC Algorithm - Type of GC Server GC Multiprocessor (MP) Scalable, Parallel One GC thread per CPU Program paused during marking Workstation GC Minimizes pauses by running concurrently during full collections
GC Algorithm - Concurrent GC Concurrent GC can be used in Workstation mode on a multi-proc machine.  Performs full collections (generation 2) concurrently with the running program, therefore minimizing the pause time.  This mode is particularly useful for applications with graphical user interfaces or applications where responsiveness is essential.  Concurrent GC is only used with generation 2; generations 0 and 1 are always non-concurrent because they finish very fast.
Configuration Type of GC Specify the GC mode in the application’s config file: <configuration><runtime><gcServer enabled=”true” /></runtime></configuration> Specify the GC mode to Concurrent: <configuration><runtime><gcConcurrent enabled=”true” /></runtime></configuration>
What’s new GC in .net framework 4 Problem: The single GC thread cannot handle two operations at same time Scanning generation 0 and 1. Space may also run out (for gen 0 and 1) before GC collection finishes. And this is the reason why Microsoft always recommended not to call GC.Collect method.
Concurrency problem
What’s new GC in .net framework 4 Approach Reduce the latency problem described above and run the collection on ephemeral segment while performing generation 2 collection.
What’s new GC in .net framework 4 Solution The Background GC: this will work as the scenario described above. Means, background GC will work on the generation 2 collection and allocation of new objects into generation 0. The Foreground GC: This will be only triggered when the ephemeral segment needs to be collected while performing a generation 2 collection.
Solution of .net framework 4
Improve performance
Improve performance Choose type of GC Server GC The server GC is designed for maximum throughput, and scales with very high performance. The Server GC uses multiple heaps and collection threads to maximize throughput and scale better. Workstation GC The Workstation GC uses the second processor to run the collection concurrently, minimizing delays while diminishing throughput
Improve performance - Finalizes In a scenario where you have resources that need to be released at a specific time, you lose control with finalizes.  N objects that require disposal in a certain order may not be handled correctly. An enormous object and its children may take up far too much memory, require additional collections and hurt performance.  A small object to be finalized may have pointers to large resources that could be freed at any time.  Disposal and finalization paths an object can take
Improve performance A Finalize() method:  Is called by the GC Is not guaranteed to be called in any order, or at a predictable time After being called, frees memory after the next GC  Keeps all child objects live until the next GC A Dispose() method:  Is called by the programmer Is ordered and scheduled by the programmer Returns resources upon completion of the method
Improve performance Recommendation Release objects when we’re done with them and keep an eye out for leaving pointers to objects.  When it comes to object cleanup, implement both a Finalize() and Dispose() method for objects with unmanaged resources. This will prevent unexpected behavior later, and enforce good programming practices.
Improve performance Identify and analyze your application's allocation profile. Avoid calling GC.Collect. Consider weak references with cached data. Prevent the promotion of short-lived objects. Set unneeded member variables to Null before making long-running calls. Minimize hidden allocations. Avoid or minimize complex object graphs.
Detect memory leak What is memory leak? A memory leak occurs when memory is allocated in a program and is never returned to the operating system.
Detect memory leak Memory leak in .Net framework: Memory is disposed of but never collected, because a reference to the object is still active.  The garbage collector can collect and free the memory but never returns it to the operating system. E.g: if that object was registered to an event published by another object, it won’t be collected by the GC  => When you register to an event => a reference from the object that published the event to the registering object.
Avoid memory leak Weak references Weak references allow the garbage collector to collect the object, but they also allow the application to access the object. Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.
Avoid memory leak Guide lines for memory leak Use long weak references only when necessary as the state of the object is unpredictable after finalization.  Avoid using weak references to small objects because the pointer itself may be as large or larger.  Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects.
Avoid memory leak Using disposable pattern Create a class that derives from IDisposable. Add a private member variable to track whether IDisposable.Dispose has already been called.  Implement a protectedvirtualvoid override of the Dispose method that accepts a single bool parameter.  Implement the IDisposable.Dispose method that accepts no parameters. call Dispose(true) and then prevent finalization by calling GC.SuppressFinalize(this).  Create a finalizer, by using destructor syntax. In the finalizer, call Dispose(false).
Detect memory leak Stack Memory Stack memory gets reclaimed after the method returns Stack memory can get leaked in two ways: A method call consumes a significant amount of stack resources that never returns The other is by creating background threads and never terminating them. Thus leaking the thread stack
Detect memory leak Unmanaged Heap Memory If the managed code is interoperating with unmanaged code and a leak exists in the unmanaged code. There exists a finalizer which blocks this thread, then the other finalizer will never get called and the unmanaged memory will leak which was supposed to be released.
Detect memory leak Managed Heap Memory Get leaked by several ways like fragmentation of the Large Object Heap.  ,[object Object]
 There exist some objects which are not needed, but there exists a reference to the objects, then GC never claims the memory assigned to these objects.,[object Object]
Detect memory leak If .NET CLR LocksAndThreads/# is increasing unexpectedly, then the thread stack is leaking. If only Process/Private bytes are increasing but the .NET CLR Memory is not increasing then unmanaged memory is leaking.  If Process/Private bytes and the .NET CLR Memory is increasing then then managed memory is leaking.
Detect memory leak Using Memprofiler or Ant Profiler Step 1: Attach process into  Step 2: Execute action on our application Step 3: Take snapshot memory Step 4: Do action again as Step 2 Step 5: Take snapshot again Step 6: Review and diagnostics memory base on significant of memory profiler.
Detect memory leak – Graph objects We can see for example that the Form is linked by a UserPreferenceChangedEventHandler through the _target member variable, in other words, one reason that the Form can’t be garbage collected is because it is handling a UserPreferenceChangedEvent.
Common scenarios leak in WPF Case 1: Unregistered events newOrder.OnPlaced += OrderPlaced; _pendingDeals.Add(newOrder); void DeleteOrder (Order placedOrder)  {  _pendingDeals.Remove(placedOrder);  }
Common scenarios leak in WPF Solution case 1: Unregistered Event before we remove or dispose object void DeleteOrder (Order placedOrder)  {  	_pendingDeals.Remove(placedOrder);  }
Common scenarios leak in WPF Case 2:DataBinding If we have a child object that data binds to a property of its parent, a memory leak can occur. <Grid Name="mainGrid">  <TextBlock Name=”txtMainText” Text="{Binding ElementName=mainGrid, Path=Children.Count}" />  </Grid>
Common scenarios leak in WPF Solution case 2: 1.  Add a DependencyProperty to the page/window returns the value of the required PropertyDescriptor property. Binding to this property instead will get solve the problem.  2.  Make the binding OneTime 3. Clear bingdings when unloaded  BindingOperations.ClearBinding(txtMainText, TextBlock.TextProperty);
Common scenarios leak in WPF Case 3:Static Events MyStaticClass.MyEvent += new EventHandler(MyHandler) public override void MyHandler(EventArgs e) {  // DO something ….. }
Common scenarios leak in WPF Solution case 3 We will unsubscribe, simply add the code line  MyStaticClass.EventToLeak -= this.AnEvent;
Common scenarios leak in WPF Case 4: Command binding CommandBindingcutCmdBinding = new CommandBinding(ApplicationCommands.Cut, OnMyCutHandler, CanExecuteCut); mainWindow.main.CommandBindings.Add(cutCmdBinding);  void OnMyCutHandler (object target, ExecutedRoutedEventArgs e)  {  // To Do Something }  void CanExecuteCut(object sender, CanExecuteRoutedEventArgs e)  {  e.CanExecute = true;  }
Common scenarios leak in WPF Solution case 4: We will clear bindings mainWindow.main.CommandBindings.Remove(cutCmdBinding);
Common scenarios leak in WPF Case 5: Dispatcher timer leak DispatcherTimer_timer = new DispatcherTimer();  intcount = 0;          private void MyLabel_Loaded(object sender, RoutedEventArgs e)          {  _timer.Interval = TimeSpan.FromMilliseconds(1000);              _timer.Tick += new EventHandler(delegate(object s, EventArgsev)              {                  count++;                  textBox1.Text = count.ToString();              });              _timer.Start();          }
Common scenarios leak in WPF Solution Case 5 We will stop timer and set null  _timer.Stop();  _timer=null;

Más contenido relacionado

Último

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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)wesley chun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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...Neo4j
 
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 MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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.pdfEnterprise Knowledge
 

Último (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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 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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 

Destacado

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Destacado (20)

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 

Garbage collector

  • 1. GC & Memory leak Author : Toan Vo
  • 2. Overview What is garbage collector (GC)? GC algorithm. Generation. Type of Garbage collector GC in .Net framework 4 Improve performance Common memory leak in WPF or Silverlight Detect memory leak.
  • 3. What is Garbage collector Automatic garbage collection is a process by which the system will automatically take care of the memory used by unwanted objects (we call them as garbage) to be released Garbage collection is a process of releasing the memory used by the objects, which are no longer referenced.
  • 4. What is Garbage collector Garbage collector as a separate thread. This thread will be running always at the back end. Lowest priority. When GC already called? When system finds there is no space in the managed heap (managed heap is nothing but a bunch of memory allocated for the program at run time). GC thread will be given REALTIME priority (REALTIME priority is the highest priority in Windows) and collect all the un wanted objects.
  • 5.
  • 6. No longer have to implement any code that. Manages the lifetime of any resources.
  • 7. It is not possible to leak resources.
  • 8.
  • 9. GC Algorithm Check from roots Build a graph objects If roots added new objects. Then add object into graph. Continue with another roots. If root added another object already in map then move to next root.
  • 10. GC Algorithm The garbage collector now walks through the heap linearly. The garbage collector then shifts the non-garbage objects down in memory removing all of the gaps in the heap.
  • 12. GC Algorithm GC Start examining all the objects in the level Generation Zero. If it finds any object marked for garbage collection, it will simply remove those objects from the memory. GC to compact the memory structure after collecting the objects GC will look which are all the objects survive after the sweep (collection). Those objects will be moved to Generation One and now the Generation Zero is empty for filling new objects. Happen with Generation One same as Generation Zero as well.
  • 13. GC Algorithm What’s happen when Gen 1 filled? Expand size of gen 2 when if it can Move all of objects still alive at Gen 1 to Gen 2 Note: If object has size 85,000 bytes or greater will start off in Generation 2 directly. Only generation 2 is allow to grow as needed.
  • 14. GC Algorithm Generation 0 (Gen 0). This consists of newly created objects. Gen 0 is collected frequently to ensure that short-lived objects are quickly cleaned up. Those objects that survive a Gen 0 collection are promoted to Generation 1. Generation 1 (Gen 1). This is collected less frequently than Gen 0 and contains longer-lived objects that were promoted from Gen 0. Generation 2 (Gen 2). This contains objects promoted from Gen 1 (which means it contains the longest-lived objects) and is collected even less frequently. The general strategy of the garbage collector is to collect and move longer-lived objects less frequently.
  • 15. GC Algorithm - Type of GC Server GC Multiprocessor (MP) Scalable, Parallel One GC thread per CPU Program paused during marking Workstation GC Minimizes pauses by running concurrently during full collections
  • 16. GC Algorithm - Concurrent GC Concurrent GC can be used in Workstation mode on a multi-proc machine. Performs full collections (generation 2) concurrently with the running program, therefore minimizing the pause time. This mode is particularly useful for applications with graphical user interfaces or applications where responsiveness is essential. Concurrent GC is only used with generation 2; generations 0 and 1 are always non-concurrent because they finish very fast.
  • 17. Configuration Type of GC Specify the GC mode in the application’s config file: <configuration><runtime><gcServer enabled=”true” /></runtime></configuration> Specify the GC mode to Concurrent: <configuration><runtime><gcConcurrent enabled=”true” /></runtime></configuration>
  • 18. What’s new GC in .net framework 4 Problem: The single GC thread cannot handle two operations at same time Scanning generation 0 and 1. Space may also run out (for gen 0 and 1) before GC collection finishes. And this is the reason why Microsoft always recommended not to call GC.Collect method.
  • 20. What’s new GC in .net framework 4 Approach Reduce the latency problem described above and run the collection on ephemeral segment while performing generation 2 collection.
  • 21. What’s new GC in .net framework 4 Solution The Background GC: this will work as the scenario described above. Means, background GC will work on the generation 2 collection and allocation of new objects into generation 0. The Foreground GC: This will be only triggered when the ephemeral segment needs to be collected while performing a generation 2 collection.
  • 22. Solution of .net framework 4
  • 24. Improve performance Choose type of GC Server GC The server GC is designed for maximum throughput, and scales with very high performance. The Server GC uses multiple heaps and collection threads to maximize throughput and scale better. Workstation GC The Workstation GC uses the second processor to run the collection concurrently, minimizing delays while diminishing throughput
  • 25. Improve performance - Finalizes In a scenario where you have resources that need to be released at a specific time, you lose control with finalizes. N objects that require disposal in a certain order may not be handled correctly. An enormous object and its children may take up far too much memory, require additional collections and hurt performance. A small object to be finalized may have pointers to large resources that could be freed at any time. Disposal and finalization paths an object can take
  • 26. Improve performance A Finalize() method: Is called by the GC Is not guaranteed to be called in any order, or at a predictable time After being called, frees memory after the next GC Keeps all child objects live until the next GC A Dispose() method: Is called by the programmer Is ordered and scheduled by the programmer Returns resources upon completion of the method
  • 27. Improve performance Recommendation Release objects when we’re done with them and keep an eye out for leaving pointers to objects. When it comes to object cleanup, implement both a Finalize() and Dispose() method for objects with unmanaged resources. This will prevent unexpected behavior later, and enforce good programming practices.
  • 28. Improve performance Identify and analyze your application's allocation profile. Avoid calling GC.Collect. Consider weak references with cached data. Prevent the promotion of short-lived objects. Set unneeded member variables to Null before making long-running calls. Minimize hidden allocations. Avoid or minimize complex object graphs.
  • 29. Detect memory leak What is memory leak? A memory leak occurs when memory is allocated in a program and is never returned to the operating system.
  • 30. Detect memory leak Memory leak in .Net framework: Memory is disposed of but never collected, because a reference to the object is still active. The garbage collector can collect and free the memory but never returns it to the operating system. E.g: if that object was registered to an event published by another object, it won’t be collected by the GC => When you register to an event => a reference from the object that published the event to the registering object.
  • 31. Avoid memory leak Weak references Weak references allow the garbage collector to collect the object, but they also allow the application to access the object. Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.
  • 32. Avoid memory leak Guide lines for memory leak Use long weak references only when necessary as the state of the object is unpredictable after finalization. Avoid using weak references to small objects because the pointer itself may be as large or larger. Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects.
  • 33. Avoid memory leak Using disposable pattern Create a class that derives from IDisposable. Add a private member variable to track whether IDisposable.Dispose has already been called. Implement a protectedvirtualvoid override of the Dispose method that accepts a single bool parameter. Implement the IDisposable.Dispose method that accepts no parameters. call Dispose(true) and then prevent finalization by calling GC.SuppressFinalize(this). Create a finalizer, by using destructor syntax. In the finalizer, call Dispose(false).
  • 34. Detect memory leak Stack Memory Stack memory gets reclaimed after the method returns Stack memory can get leaked in two ways: A method call consumes a significant amount of stack resources that never returns The other is by creating background threads and never terminating them. Thus leaking the thread stack
  • 35. Detect memory leak Unmanaged Heap Memory If the managed code is interoperating with unmanaged code and a leak exists in the unmanaged code. There exists a finalizer which blocks this thread, then the other finalizer will never get called and the unmanaged memory will leak which was supposed to be released.
  • 36.
  • 37.
  • 38. Detect memory leak If .NET CLR LocksAndThreads/# is increasing unexpectedly, then the thread stack is leaking. If only Process/Private bytes are increasing but the .NET CLR Memory is not increasing then unmanaged memory is leaking. If Process/Private bytes and the .NET CLR Memory is increasing then then managed memory is leaking.
  • 39. Detect memory leak Using Memprofiler or Ant Profiler Step 1: Attach process into Step 2: Execute action on our application Step 3: Take snapshot memory Step 4: Do action again as Step 2 Step 5: Take snapshot again Step 6: Review and diagnostics memory base on significant of memory profiler.
  • 40. Detect memory leak – Graph objects We can see for example that the Form is linked by a UserPreferenceChangedEventHandler through the _target member variable, in other words, one reason that the Form can’t be garbage collected is because it is handling a UserPreferenceChangedEvent.
  • 41. Common scenarios leak in WPF Case 1: Unregistered events newOrder.OnPlaced += OrderPlaced; _pendingDeals.Add(newOrder); void DeleteOrder (Order placedOrder) { _pendingDeals.Remove(placedOrder); }
  • 42. Common scenarios leak in WPF Solution case 1: Unregistered Event before we remove or dispose object void DeleteOrder (Order placedOrder) { _pendingDeals.Remove(placedOrder); }
  • 43. Common scenarios leak in WPF Case 2:DataBinding If we have a child object that data binds to a property of its parent, a memory leak can occur. <Grid Name="mainGrid"> <TextBlock Name=”txtMainText” Text="{Binding ElementName=mainGrid, Path=Children.Count}" /> </Grid>
  • 44. Common scenarios leak in WPF Solution case 2: 1. Add a DependencyProperty to the page/window returns the value of the required PropertyDescriptor property. Binding to this property instead will get solve the problem. 2. Make the binding OneTime 3. Clear bingdings when unloaded BindingOperations.ClearBinding(txtMainText, TextBlock.TextProperty);
  • 45. Common scenarios leak in WPF Case 3:Static Events MyStaticClass.MyEvent += new EventHandler(MyHandler) public override void MyHandler(EventArgs e) { // DO something ….. }
  • 46. Common scenarios leak in WPF Solution case 3 We will unsubscribe, simply add the code line MyStaticClass.EventToLeak -= this.AnEvent;
  • 47. Common scenarios leak in WPF Case 4: Command binding CommandBindingcutCmdBinding = new CommandBinding(ApplicationCommands.Cut, OnMyCutHandler, CanExecuteCut); mainWindow.main.CommandBindings.Add(cutCmdBinding); void OnMyCutHandler (object target, ExecutedRoutedEventArgs e) { // To Do Something } void CanExecuteCut(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; }
  • 48. Common scenarios leak in WPF Solution case 4: We will clear bindings mainWindow.main.CommandBindings.Remove(cutCmdBinding);
  • 49. Common scenarios leak in WPF Case 5: Dispatcher timer leak DispatcherTimer_timer = new DispatcherTimer(); intcount = 0; private void MyLabel_Loaded(object sender, RoutedEventArgs e) { _timer.Interval = TimeSpan.FromMilliseconds(1000); _timer.Tick += new EventHandler(delegate(object s, EventArgsev) { count++; textBox1.Text = count.ToString(); }); _timer.Start(); }
  • 50. Common scenarios leak in WPF Solution Case 5 We will stop timer and set null _timer.Stop(); _timer=null;
  • 51. Common scenarios leak in WPF Case 5b: TEXTBOX UNDO LEAK Not really leak but it take longer time when release memory Solution: Fixed by Disable undo ability textBox1.IsUndoEnabled=false; Or textBox1.UndoLimit=100;
  • 52. Q & A Reference http://msdn.microsoft.com/en-us/magazine/bb985010.aspx http://msdn.microsoft.com/en-us/library/ms404247.aspx http://support.microsoft.com/kb/318263/en-us?fr=1 http://www.codeproject.com/KB/dotnet/Memory_Leak_Detection.aspx http://blogs.msdn.com/b/ricom/archive/2004/12/10/279612.aspx http://blogs.msdn.com/b/delay/archive/2009/03/11/where-s-your-leak-at-using-windbg-sos-and-gcroot-to-diagnose-a-net-memory-leak.aspx http://memprofiler.com/instancegraph.aspx http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/learning-memory-management/WPF-silverlight-pitfalls

Notas del editor

  1. However, keep in mind that GCs only occur when the heap is full and, until then, the managed heap is significantly faster than a C-runtime heap
  2. E.g : all the global and static object pointers are considered as application rootsLocal variable/parameter object pointers on a thread stack are considered as a part of application roots
  3. Of course, moving the objects in memory invalidates all pointers to the objects. So the garbage collector must modify the application&apos;s roots so that the pointers point to the objects&apos; new locations. In addition, if any object contains a pointer to another object, the garbage collector is responsible for correcting these pointers as well.
  4. When Generation Zero is full and it does not have enough space to occupy other objects but still the program wants to allocate some more memory for some other objects, then the garbage collector will be given the REALTIME priority and will come in to picture.Now the garbage collector will come and check all the objects in the Generation Zero level. If an object’s scope and lifetime goes off then the system will automatically mark it for garbage collection.
  5. If Generation One does not have space for objects from Generation Zero, then the process happened in Generation Zero will happen in Generation one as well.All the generations are filled with the referred objects and still system or our program wants to allocate some objects, then what will happen? If so, then the MemoryOutofRangeException will be thrown.
  6. Usually Gen 0 was 256KB (fits the cpu&apos;s l2 cache ) Gen1 2MB Gen2 10MB
  7. The server GC is designed for maximum throughput, and scales with very high performance.The Server GC uses multiple heaps and collection threads to maximize throughput and scale better.The Workstation GC uses the second processor to run the collection concurrently, minimizing delays while diminishing throughput
  8. It will start marking the objects, checking the stacks and the GC roots. This operation will allow further allocations, this means that your application may create a new object and this will be allocated in generation 0.Now there are further allocations that the GC needs to suspend the EE (Execution engine) and this will stop all threads on your application. At this stage no allocation is allowed and your application may suffer some latency.The EE is resumed in order to continue working on the heap and other bits and pieces that the GC needs to handle; at this stage the allocation is allowed. But what happen if our ephemeral segment is full while this collection happens?At this stage the ephemeral collection cannot swap segments and the allocation will be delayed, adding latency to your application.
  9. The ephemeral foreground thread will mark the dead objects and will swap segments (as this is more efficient rather than copying the objects to generation 2. The ephemeral segment with the free and allocated objects becomes a generation 2 segment. As you can see now the allocation is allowed and your application will not need to wait for the full GC to finish before allowing you the allocation.
  10. A reference to the object is still active, the garbage collector never collects that memory. This can occur with a reference that is set by the system or the program. The garbage collector can collect and free the memory but never returns it to the operating system. This occurs when the garbage collector cannot move the objects that are still in use to one portion of the memory and free the rest.Poor memory management can result when many large objects are declared and never permitted to leave scope. As a result, memory is used and never freed.
  11. the framework has to subscribe to the ValueChangedevent, which in turn sets up a strong reference chain.
  12. Subscribing to an event on a static object will set up a strong reference to any objects handling that event. And strong references preventing garbage collection are just memory leaks by another name.