Java 的 LinkedList 中的 clear() impl [英] clear() impl in Java's LinkedList

查看:25
本文介绍了Java 的 LinkedList 中的 clear() impl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我担心这是一个非常愚蠢的问题,但这里是:

I fear this is a really stupid question, but here goes:

为什么 Java 的默认 LinkedList 实现中的 clear 方法麻烦地遍历列表并解开所有节点?为什么不直接解开标题并让列表的其余部分保持连接——GC 无论如何都会得到它,不是吗?

Why does the clear method in Java's default LinkedList implementation bother to walk the list and unhook all the nodes? Why not just unhook the header and leave the rest of the list connected -- the GC will get it anyway, no?

方法如下:

/**
 * Removes all of the elements from this list.
 */
public void clear() {
    Entry<E> e = header.next;
    while (e != header) {
        Entry<E> next = e.next;
        e.next = e.previous = null;
        e.element = null;
        e = next;
    }
    header.next = header.previous = header;
    size = 0;
modCount++;
}

为什么要走呢?为什么不直接跳到 header.next = header.previous = header;?

Why walk it? Why not just skip to header.next = header.previous = header;?

我能想到的最好的方法是它对 GC 有帮助...?此链接 http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html#997442 有点暗示这一点.

Best I can figure is it helps the GC...? This link http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html#997442 sort of suggests that.

TIA...

推荐答案

他们的方法确保即使其他代码仍然持有对特定节点的引用,其他节点也会被 GC 处理.

Their method ensures that even if other code still holds references to particular nodes, the other nodes will be GC'ed.

否则,即使是对其中一个节点的单个外部引用也会阻止收集整个链.

Otherwise, even a single external reference to one of the nodes would prevent the entire chain from being collected.

此外,列表中的其他操作可能会同时进行(例如通过 subList()Collections.unmodifiableList() 进行查看,迭代器),这确保这些东西立即将列表视为空".

Also, other operations in the list might be going on simultaneously (e.g. views through subList() or Collections.unmodifiableList(), iterators), and this ensures that those things perceive the list as "empty" immediately.

这篇关于Java 的 LinkedList 中的 clear() impl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆