【发布时间】:2018-07-16 02:18:34
【问题描述】:
我不知道如何搜索这个问题,所以我问了一个问题。
Java 版本 1.7.0_80_x86java.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