垃圾收集器是否会收集不再可访问但仍指向该树的树叶

Hoo*_*lum 2 java tree garbage-collection binary-search-tree

在这种情况下会发生什么?即使它仍然引用了树,它也会被收集吗?

class BinarySearchTree {
    TreeNode root;
    /* constructor  including assigning the root*/
    /* other methods of the tree */
    public void example() {
        root = null; /* assume the root already has children */
                         /* we haven't set the parent of the child of the root*/
                          /*to null*/
    }
}

class TreeNode {
    private TreeNode left;
    private TreeNode right;
    private TreeNode parent;

    /* set and get methods */
}
Run Code Online (Sandbox Code Playgroud)

Hot*_*cks 5

垃圾收集器从“根”开始。这些将是由 JVM 锚定的几个表以及所有线程的所有堆栈帧中的所有引用。每个“根”引用都被“跟踪”到它所寻址的任何对象,并且该对象被添加到可到达但未跟踪的对象的列表中。

跟踪根之后,一次检查一个可到达但未跟踪的对象列表,并将这些对象中的引用“跟踪”到其他对象,然后将这些对象添加到列表中。

一旦追踪到对象,它们就会从列表中删除。在遵循引用时到达的对象以及结果已经被触摸的对象不会添加到列表中。

最终,可到达但未跟踪的对象列表变空,此时“标记”阶段完成。然后是“扫描”阶段——扫描所有对象,并丢弃任何未到达的对象。

当然,这是 GC 的一个过于简化的版本,但它几乎涵盖了所有内容。如上所述无法“到达”的对象将被“收集”,并将其空间返回到空闲空间池。