Generational Garbage collection Vs Garbage collect

2019-08-15 06:33发布

问题:

I read about GC and I realized there is not one way that the GC works but two?

First is the normal GC:

  1. Detect the garbage objects using the application roots
  2. Gather the objects to free, in the freachable queue
  3. Call the finalize method of all the object in the freachable queue
  4. Erase all the finalized objects in the next GC round.

The second is generational GC:

  1. Scan the objects and detect the objects to free and erase them
  2. Pass the ones that survived to generation 2 (to scan them less times)
  3. Pass the most survived objects to generation 3.

I'm totally confused: are these two different types of GC? Or is the generational GC is like an upgrade of the first? Or is it the same?

What is the way that the .NET works?

回答1:

.NET is generational pretty much as you described. "Something" triggers a GC pass. Survivors of this pass are promoted to the next generation and so on until Generation 2 (starting at Gen 0, so a total of 2 promotions).

GC passes higher up in the generations are fewer between because they can be more expensive.

This blog (and many other sources on the net) gives a good overview of GC in .NET:

http://dotnetfacts.blogspot.co.uk/2008/05/how-garbage-collector-works-part-1.html

http://dotnetfacts.blogspot.co.uk/2008/05/how-garbage-collector-works-part-2.html

What you have described appears to be the two halves to the .NET story. I believe your overview about the finalizer and internal queues (freachable) are mostly accurate (not sure), but so is the generation behaviour.

This SO question also dips its toe in similar waters:

Garbage Collection in .Net implementaion, objects behavior is unknown, unable to understand their behavior



回答2:

Your first point is applicable when destructor/finalizer is implemented inside your class. Its entry will be added to finalization queue at the time of initializing its object. When this object is no longer referenced by the GC Root (e.g. stack references, static object references, CPU Registers ...) apart from finalization/fReachable queue (both acts as GC Root) then this entry is moved to fReachable queue. This queue is monitored by a separate thread which is responsible to call the finalize method of this object.

Following link is an ultimate reference for understanding the memory management under .NET environment. First two chapters (around 40 pages) will give you an excellent and deep idea about how a garbage collections works under .NET environment. Most of all it is FREE eBook.

Under the Hood of .NET Memory Management By Chris Farrell and Nick Harrison

Direct Link

I recommend this book to every .NET Guy who want to write efficient programs using .NET Technology.