【问题标题】:Java source HashtableJava源码哈希表
【发布时间】:2018-07-16 02:18:34
【问题描述】:

我不知道如何搜索这个问题,所以我问了一个问题。
Java 版本 1.7.0_80_x86
java.util.Hashtable中的remove方法;
我看到节点e的value属性设置为null;
但是,e.next 没有设置为 null;
那么如果e.next不为null,节点e会不会被gc回收?
方法源码:

/**
 * Removes the key (and its corresponding value) from this
 * hashtable. This method does nothing if the key is not in the hashtable.
 *
 * @param   key   the key that needs to be removed
 * @return  the value to which the key had been mapped in this hashtable,
 *          or <code>null</code> if the key did not have a mapping
 * @throws  NullPointerException  if the key is <code>null</code>
 */
public synchronized V remove(Object key) {
    Entry tab[] = table;
    int hash = hash(key);
    int index = (hash & 0x7FFFFFFF) % tab.length;
    for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) {
        if ((e.hash == hash) && e.key.equals(key)) {
            modCount++;
            if (prev != null) {
                prev.next = e.next;
            } else {
                tab[index] = e.next;
            }
            count--;
            V oldValue = e.value;
            e.value = null;
            return oldValue;
        }
    }
    return null;
}

【问题讨论】:

  • 为什么e.next的值会阻止e的GC?由于e 本身不可访问,e 被回收。
  • 为什么不呢?任何代码都无法再访问e。是的,e.next 仍然可以到达(并且不会被垃圾收集,它仍然在表中)。但是您希望 e 被垃圾回收。
  • @Andreas 我似乎来错地方了。 e.next 不是持有另一个对象吗?可以回收吗?
  • 由于不再引用它,它将被 GC 回收,e.next 持有对另一个对象的引用,而不是持有另一个对象
  • @Michael 是的,e.next 可能持有另一个对象,该对象尚未(也不应该)从哈希表中删除。不再使用并将被回收的是e 本身,而不是e.next。 --- 另请注意,由于e 将被回收,e.value = null 是多余的,但它(被误导?)尝试帮助垃圾收集器。

标签: java garbage-collection hashtable


【解决方案1】:

每个对象树都必须有一个或多个根对象。只要应用程序可以到达这些根,如果应用程序无法到达这些根,它们就会被视为活动对象,那么它们就会被垃圾收集器收集。所以对你的问题的回答是肯定的,“e”将被 GC 收集起来。但是“e.next”可能会或可能不会被 GC 垃圾收集。如果它们是对“e.next”(“e”除外)的引用,那么它将不会被 GC 垃圾收集。

【讨论】:

    猜你喜欢
    • 2012-09-16
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 2012-09-02
    相关资源
    最近更新 更多