Baby’s First Garbage Collector › 少使用、物尽其用、循环再用 Reduce, reuse, recycle [#264]

垃圾回收背后的基本思想是该语言(在大多数情况下)似乎可以访问无限的内存。开发者可以不断地分配、分配、分配,就像变魔术一样,内存永远不会用完。
The basic idea behind garbage collection is that the language (for the most part) appears to have access to infinite memory. The developer can just keep allocating and allocating and allocating and, as if by magic, never run out.

当然,计算机并不具有无限的内存。因此,实现这个魔术的方式是,当它需要分配一些内存并意识到内存不足时,它会回收垃圾
Of course, machines don’t have infinite memory. So the way the implementation does this is that when it needs to allocate a bit of memory and it realizes it’s running low, it collects garbage.

在这个语境中,“垃圾”是指之前分配的,现在不再使用了的内存。为了让无限内存的幻觉发挥作用,语言需要非常安全地“不再被使用”。当你的程序试图访问随机对象,如果这时它们就开始被回收,那就不好玩了。
“Garbage” in this context means memory it previously allocated that is no longer being used. For the illusion of infinite memory to work, the language needs to be very safe about “no longer being used”. It would be no fun if random objects just started getting reclaimed while your program was trying to access them.

为了可回收,该语言必须确保程序无法再次使用该对象。如果程序无法获取该对象的引用,那么它显然无法再次使用它。所以“使用中”的定义实际上非常简单:
  1. 任何被仍在作用域中的变量引用的对象都正在使用中。
  2. 任何被另一个正在使用的对象引用的对象都在使用中。
In order to be collectible, the language has to ensure there’s no way for the program to use that object again. If the program can’t get a reference to the object, then it obviously can’t use it again. So the definition of “in use” is actually pretty simple:
  1. Any object being referenced by a variable still in scope is in use.
  2. Any object referenced by another in-use object is in use.

第二条规则是递归规则。如果对象 A 被变量引用,并且它有一些引用对象 B 的字段,则 B 正在使用中,因为你可以通过 A 访问它。
The second rule is the recursive one. If object A is referenced by a variable, and it has some field that references object B, then B is in use since you can get to it through A.

最后我们得到的是可达对象的图⸺可达对象即所有可以从一个变量开始,遍历其对象来到达的对象。任何不在可达对象图中的对象对于程序来说都是死的,它的内存已经时机成熟,可以被回收了。
The end result is a graph of reachable objects—all of the objects in the world that you can get to by starting at a variable and traversing through objects. Any object not in that graph of reachable objects is dead to the program and its memory is ripe for a reaping.