2014-10-28 63 views
0

我讀了一些關於Java內存泄漏的內容。它使用陣列實現FIFO隊列以語義泄漏內存。但我不明白爲什麼它會導致內存泄漏。是因爲它沒有使'流行'操作中的未使用的插槽無效?任何人都可以向我解釋?FIFO隊列實現中的Java內存泄漏

queue[head] = null 

的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; 
     } 
    } 
+0

出於好奇,你需要手動實現一個隊列,而不是使用現有的['Queue']之一(http://docs.oracle.com/javase/8/docs/api/java/util/ Queue.html)的實現?例如,['ArrayDeque'](http://docs.oracle.com/javase/8/docs/api/java/util/ArrayDeque.html)聽起來像是你想要在這裏做同樣的事情(除了它是[雙端隊列](http://docs.oracle.com/javase/8/docs/api/java/util/Deque.html)) – Powerlord 2014-10-28 05:42:00

+0

這似乎基本上是在這裏問的同一個問題: http://stackoverflow.com/questions/2843799/why-does-this-code-sample-produce-a-memory-leak?rq=1 但我不明白的是如何ensureCapacity()是正確的在隊列環繞數組末尾(這是常見的情況)的情況下,只需調整大小不會使'queue [head]'可用。 – hcs 2014-10-28 05:59:52

回答

0

你回答了你自己的問題:)

,因爲你不乾淨的隊列引用垃圾收集器,不能從清理內存,因爲你在FIFOQueue中有對這個對象的有效引用。這樣你就會用未使用的對象污染你的記憶,減少你的程序有效使用的記憶。

同樣如評論中指出的那樣,只有在尾部位於數組末尾時,您的ensureCapasity函數纔會起作用,否則在推送時會丟失隊列中的元素,這對於隊列[head]參考問題。

+0

謝謝。我也發現這個鏈接http://cs.lmu.edu/~ray/notes/queues/,它也提到了不會取消對象引用的內存泄漏。 – GarudaReiga 2014-10-28 06:07:14

+0

如果您經常使用隊列,您最終會用新的參考替換舊的參考,從而有效地將其釋放用於GC。 – mavarazy 2014-10-28 06:14:47