java - 什么是java中的过时引用

标签 java

I'm reading the Effective Java book and its saying that eliminating obsolete reference is one of best way to avoid memory leaks. according to the below program, by doing -> elements[size] = null; its eliminating obsolete references in that program. My problem here what is the advantage of doing elements[size] = null;. Any other program can use that freed memory location? Or is it garbage collected? According to my understanding the array is already allocated the memory for its size. Even we do elements[size] = null; anyone can't use that freed memory location until you do elements = null;. Please someone tell me what is advantage of doing elements[size] = null; here.

public Object pop() {
    if (size == 0)
        throw new EmptyStackException();
    Object result = elements[--size];
    elements[size] = null; // Eliminate obsolete reference
    return result;
}

最佳答案

My problem here what is the advantage of doing elements[size] = null;.

这里过时的引用是指程序不再需要的对象引用。
您希望那些不必要的对象可以自由使用,只消耗您的程序所需的内存。通常它是为了当前应用程序的良好工作而完成的。

Any other program can use that freed memory location?

理论上是的,但它也取决于所使用的 JVM 内存选项。你通常不会专注于它。

elements[size] = nullelements = null; 根本没有相同的意图和相同的效果。

在本书的上下文中,elements是一个类的结构实习生。
这个想法是数组的某些元素可能已经过时并且在一些删除操作之后不再需要。

第一个(elements[size] = null)将使位于size索引处的数组元素的对象有资格被GC,如果没有其他对象引用。
但第二个 (elements = null) 远不止于此。如果没有其他对象引用它,它将使数组的所有元素都有资格成为 GC。

关于java - 什么是java中的过时引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54609076/

相关文章:

java - Linux 服务器不支持西类牙字符

java - servlet - 许多上下文 - 如何共享数据库连接?

java - 向下滚动时 ListView 图标出现在错误的行中

java - 如何在 jsp 文件中检索 session 对象(由 servlet 存储)?

java - pop()ing 堆栈似乎并没有删除这些值

java - 使用cssSelector清除Chrome浏览器的浏览数据时,如何与#shadow-root(打开)中的元素进行交互

java - 并行继承层次结构真的是一种代码味道吗?

java - 尝试从另一个方法调用 ArrayList

java - 通过 Java servlet 检测操作系统或计算机名称

JavaFX 在运行时关闭 Textfield 的虚拟键盘或通过代码一段时间