What is a root reference?

class GCTest {
     static Object r1; 

     static void Main() {
         r1 = new Object();
         Object r2 = new Object();
         Object r3 = new Object();
         System.GC.Collect(); // what can be reclaimed here ?

         r1 = null;
         r3.ToString();
         System.GC.Collect(); // what can be reclaimed here ?
     }
    }

// code from - DonBox Essential.Net

+3
source share
6 answers

There r2are no further links in the first line , so this object can be restored at that moment. The last line of an object created for r1, has no more links, and local variables r2, and r3completed, so all three objects can be restored at this time. However, this will depend on how it is compiled.

, . r1 , , GCTest r1 .

+3

WeakReference, , . . GC r1. WeakReference , .

, , . , r3.ToString() , , iff r3 null.

+2

GC , , . : , , .

, GC.Collect(), r1, r1 - , - "". GC , GC , . . , , . ( ), GC , r2 (GC , , , GC ). GC ( ).

- GC.Collect(): ToString() . , GC . , , VM , Object ( - ), ToString() , ToString() ( ). , GC ToString().

, GC , . GC , " ", ( , , , ).

Wilson , , .

+2

. .. A B B C .. A , .

.

r1 GC- , , r2 . r3 , GC.KeepAlive

r1 , r2 , r3, , .

0
  • Main() r1, , , r1 null.
  • r2 r3 - Main(), .
0

, :

. (1994):

, .

0

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


All Articles