简体   繁体   English

FIFO队列实现中的Java内存泄漏

[英]Java Memory Leak in FIFO queue implementation

I read some material about Java memory leak. 我读了一些有关Java内存泄漏的材料。 It implements FIFO Queue with array to semantically leak memory. 它使用数组实现FIFO队列以语义上泄漏内存。 But I don't understand why it will cause memory leak. 但是我不明白为什么它会导致内存泄漏。 Is it because it didn't nullify the unused slot in the 'pop' operation? 是否因为它没有使“ pop”操作中未使用的插槽无效? Anyone can explain to me? 有人可以向我解释吗?

queue[head] = null

The FIFO Queue implementation is as follows: FIFO队列实现如下:

public class FIFOQueue {     
    private Object[] queue;     
    private int size = 0, head = 0, tail = 0;
    private static final int INITIAL_CAPACITY = 16;     

    public FIFOQueue() {         
        queue = new Object[INITIAL_CAPACITY];
    }

    public void push(Object e) {         
        ensureCapacity();         
        queue[tail] = e;
        size++;  
        tail = increment(tail); 
    }

    public Object pop() throws EmptyStackException {         
        if (size == 0)             
            throw new EmptyStackException();         
        size–;
        Object returnValue = queue[head];
        head = increment(head);
        return returnValue;
    }  

    /**  doubling the capacity each time the array needs to grow.      */     
    private void ensureCapacity() {        
        if (queue.length == size)             
            queue = Arrays.copyOf(queue, 2 * size + 1);     
    }

    /** make sure the pointers are wrapped around at the end of the array */
    private int increment( int x ) {
        if( ++x == queue.length )
            x = 0;
            return x;
        }
    }

You answered your own Question:) 你是在自问自答:)

Since you don't clean queue reference Garbage Collector, can't clean it from memory, because you have valid reference to this Object in your FIFOQueue. 由于您不清除队列引用垃圾收集器,因此无法从内存中清除它,因为您在FIFOQueue中具有对该对象的有效引用。 That way you pollute your memory with unused Objects, reducing memory effectively available to your program. 这样,您将使用未使用的对象污染内存,从而减少了程序可以有效使用的内存。

Also as pointed in comments, your ensureCapasity function will only work, when the tail is at the end of an array, otherwise you'll be loosing elements in your queue on push, this is more critical then queue[head] reference problem. 另外,正如注释中所指出的那样,当尾部位于数组的末尾时,您的sureCapasity函数将仅起作用,否则您将在推入队列中失去元素,这比queue [head]引用问题更为关键。

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

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