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

查看:131
本文介绍了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 ......

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天全站免登陆