Garbage collection circular object links

Suppose I have 2 objects - object A and object B. Object A of the link Object B and object B of the link Object A.

  • If both objects A and object B do not match the code, how does the garbage collector know that it can be collected.
  • How did the garbage collector deduce that any object is out of scope / ready to collect garbage?
  • How about whether Object A will not match our code, but it can still be independent. For instance. if it is a form class, then it can start on its own, even if object A is reinitialized in a new instance or specified zero.
+6
source share
2 answers
  • GC does not select an object and does not see if anything refers to it; keeping it if that happens. GC has a collection of every object that he knows is "alive." This collection begins as all static variables, all variables on the stack, and several other special cases. Then he goes through each of these โ€œlivingโ€ objects and sees which objects they refer to. Each referenced object is itself designated as โ€œliving,โ€ because it means that it is somehow accessible to another living object. He repeats this process until new objects are discovered. As you know, everything that was not marked as living is inaccessible. As you can tell, since you never checked which links to any given "dead" object, regardless of whether the circular link exists, does not matter.

  • See No. 1.

  • Well, in most cases this is mentioned somewhere; in the case of a form, for example, you have Application.OpenForms link to any open forms. Similar designs often exist for such objects. In rare cases with objects such as timers, they are not explicitly communicated to the GC so that they are not collected. Such situations are very rare, and you usually do not need to worry about them.

+6
source
  • The garbage collector scans the active links, and everything that is not found can be collected. Thus, it does not matter that these two objects refer to each other, since both of these links are inactive.

  • See 1.

  • The form is a component, so it is kept alive, being registered as one. After initialization, the program itself keeps it alive until the form is deleted. The presence of a variable that refers to the form, and then sets the variable to null, only changes the link, it does nothing for the object itself.

0
source

Source: https://habr.com/ru/post/945192/


All Articles