2021年4月6日星期二

how does concurrent garbage collection works?

We know that background garbage collection replaces concurrent garbage collection and is available in .NET Framework 4 and later versions. I still have some questions on old concurrent garbage collection in order to better understand background garbage collection.

Below is the quote from the book CLR via C# on concurrent garbage collection:

the GC can run in two sub-modes: concurrent (the default) or nonconcurrent. In concurrent mode, the GC has an additional background thread that marks objects concurrently while the application runs. When a thread allocates an object that pushes generation 0 over its budget, the GC first suspends all threads and then determines which generations to collect. If the garbage collector needs to collect generation 0 or 1, it proceeds as normal. However, if generation 2 needs collecting, the size of generation 0 will be increased beyond its budget to allocate the new object, and then the application's threads are resumed. While the application's threads are running, the garbage collector has a normal priority background thread that finds unreachable objects. Once found, the garbage collector suspends all threads again and decides whether to compact memory.

so my understanding is, there is a dedicate thread to mark (only mark, not sweep) generation 2 objects while application threads can still executes, but I see a problem here, then the dedicated thread marks a generation 2 objects unreachable, one application thread might assign a root variable to the objects to make it reachable again, then GC will wrongly collect/delect this object, which is obviously disastrous.

So when the dedicate thread running to mark generation 2 objects in heap, the heap (or portion of heap that contains generation 2 objects) must be locked to prevent accesses by other application threads. But isn't it very inefficient as CLR needs to track all application threads to make sure they are not reassiging roots to generation 2 objects, so a lot of thread context switches involved, applications experience intermediate pauses, which is no better than non-concurrent garbage collection?

https://stackoverflow.com/questions/66978646/how-does-concurrent-garbage-collection-works April 07, 2021 at 10:06AM

没有评论:

发表评论