.NET Garbage Collector

How does the garbage collector know that objects and variables are out of scope, so they can be garbage collected?

+3


source to share


3 answers


In short: every application has a set of roots. Roots define storage locations that refer to objects in the managed heap or objects that are set to null.

When the garbage collector starts working, it makes the assumption that all objects are in the garbage heap.

The garbage collector starts traversing the roots and plotting all objects accessible from the roots.



All inaccessible objects are removed (memory is freed)

This is taken from http://msdn.microsoft.com/en-us/magazine/bb985010.aspx - a good article on garbage collection. The "interesting" part for you is the "Garbage Collection Algorithm". This is not a very long section.

+6


source


A discussion of garbage collection in .NET would not be complete without reference to Raymond Chen's excellent blog series:

Here's a quote from the first article in the series:

When you ask someone what garbage collection is, the answer you get is likely to be something like: "Garbage collection is when the operating environment automatically reclaims memory that is no longer in use by a program. By tracking memory. starting at the roots to determine which objects are available. "

This description confuses the mechanism with the target. It's like saying that a firefighter's job is to "drive a red truck and spray water." This is a description of what the firefighter is doing, but it does not fit the point of work (namely, putting out fires and, more generally, fire safety).

And here are some interesting points that he demonstrates:

A properly written program cannot assume that finalizers will ever execute.

 



An object in a block of code may become suitable for collection during the execution of the function it has named.

 



A method parameter can become collectable while the method is still executing.

 



An odd real-world analogy: A garbage collector can collect your dive panel as soon as the diver touches it one last time - even if the diver is still airborne!

and, most succinctly:

Don't think of GC as tracing roots. Think about GC is something you don't use anymore.

+2


source


Go to http://msdn.microsoft.com/en-us/magazine/bb985010.aspx . As they say

The garbage collector checks to see if there are any objects on the heap that are no longer used by the application. If such objects exist, then the memory used by these objects can be reclaimed.

-4


source







All Articles