垃圾收集器将做什么

垃圾收集器将做什么

本文介绍了在这种情况下,垃圾收集器将做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解GC将如何起作用的两种情况

There are two scenario that i trying to understand how will GC will act

1-有两个对象-object1和object2
object1引用了object2和object2引用了object1
现在,这两个对象均未使用,GC可以收集它们。

1- There is two object - object1 and object2object1 has reference on object2 and object2 has reference on object1Now, both of those object are not in use and GC can collect them.

会发生什么? GC会跳过此集合吗? ?

What will happened ? does GC skip on this collection ? ?

2-同样的问题,但我们有4个(或n)相互引用的对象。
在这种情况下,GC将如何处理?

2- Same question but we have 4 ( or n ) objects that have reference on each other.What GC will do on this case ???

推荐答案

.NET使用的GC是(标记和清除是一个相关术语)

The GC used by .NET is a tracing garbage collector ("Mark and Sweep" is a related term)

内存对象被视为垃圾如果不能再通过遵循程序内存中非垃圾部分的指针/引用来达到它们。

Memory objects are considered "garbage" if they can no longer be reached by following pointers/references from the non-garbage part of your program's memory.

要确定什么是可达的,什么是不可达的,GC首先建立一组根引用/指针。这些是保证可以访问的参考。示例包括局部变量和静态字段。

To determine what is reachable and what is not, the GC first establishes a set of root references/pointers. Those are references that are guaranteed to be reachable. Examples include local variables and static fields.

然后递归地遵循这些引用(跟踪),并将遇到的每个对象标记为非垃圾。一旦它用完了要遵循的引用,它将进入清除阶段,在该阶段将释放每个未标记为非垃圾的对象(这可能包括调用该对象的终结器)。

It then follows these references recursively (traces) and marks each object it encounters as "not garbage". Once it runs out of references to follow, it enters the "sweep" phase where every object that has not been marked as "non garbage" is freed (which might include invoking the object's finalizer).

因此,只要活动对象的任何部分都没有引用对象环中的任何对象,就会对其进行垃圾回收。

So as soon as none of the objects in your "object ring" is referenced by any part of your "live" objects, it will be garbage collected.

这篇关于在这种情况下,垃圾收集器将做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:46