简体   繁体   English

为什么该程序会导致内存泄漏?

[英]Why this program can cause memory Leak?

Well , i was going through Memory Leaks in Java . 好吧,我正在经历Java中的Memory Leaks。

I saw this simple below program where the author says that Memory Leaks are possible with this below program 我看到了下面这个简单的程序,作者说下面的程序可能会导致内存泄漏

But could please tell me whats wrong with this program and why it can produce a Memory Leak ?? 但是请告诉我这个程序有什么问题以及为什么它会产生内存泄漏?

package com.code.revisited.memoryleaks;


public class StackTest {

    public static void main(String[] args) {
        Stack<Integer> s = new Stack<>(10000);
        for (int i = 0; i < 10000; i++) {
            s.push(i);
        }

        while (!s.isEmpty()) {
            s.pop();
        }

        while(true){
            //do something
        }

    }

}

pop method is removing Integer objects from the Stack . pop方法是从Stack删除Integer对象。 But Integer objects are not de-referenced; 但是Integer对象没有被取消引用。 this means that they will occupy memory. 这意味着它们将占用内存。

Update : 更新

This point is explained in Item 6 of Effective Java : Eliminate obsolete object references 关于这一点,请参见Item 6 of Effective Java消除过时的对象引用

If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects. An obsolete reference is simply a reference that will never be dereferenced again.

The fix for this sort of problem is simple: null out references or remove object from Stack once they become obsolete. 解决这类问题的方法很简单:将引用废除或将其废弃后将其从堆栈中删除。 In given case pop method will decrement the top reference. 在给定的情况下,pop方法将减少顶部引用。

It really depends how the stack is implemented. 这实际上取决于堆栈的实现方式。

If this is Java's stack (java.util.Stack), then it should not happen. 如果这是Java的堆栈(java.util.Stack),则不应发生。 The underlying array is dynamic and may have unused slots, but they are explicitly set to null when popping items. 基础数组是动态的,可能有未使用的插槽,但是在弹出项目时将其显式设置为null。

I guess that the stack in your example is not the standard one; 我猜您的示例中的堆栈不是标准堆栈; It's probably a part of the example, and it illustrates this kind of memory leak. 它可能是示例的一部分,它说明了这种内存泄漏。 For example, if the pop() method decreases the underlying array index, but doesn't set the array item to null, then the code above should leave 1000 live objects in the heap, although they are probably not needed anymore by the program. 例如,如果pop()方法减少了基础数组索引,但未将数组项设置为null,则上面的代码应在堆中保留1000个活动对象,尽管程序可能不再需要它们。

-- Edit -- -编辑-

Did you take the example from http://coderevisited.com/memory-leaks-in-java/ ? 您是否从http://coderevisited.com/memory-leaks-in-java/中获取了示例? If so, note that it also includes a stack implementation, just as I suspected. 如果是这样,请注意,正如我所怀疑的,它还包括一个堆栈实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM