As long as no items in the queue are mentioned anywhere in your code, the garbage collector will be able to return this memory. Setting pointers to null in Java is not the same as setting in C, where setting the malloc'ed pointer to null prevents it from being freed. In Java, memory is restored when it is no longer available. There are no memory leaks in Java (in the sense of C / C ++) unless you use native code through JNI.
A simplified garbage collector will simply count the number of references to an object and free this object when the reference count reaches zero, but it will not deal with reference loops (A → B, A → B → C → A, etc.). Java GC algorithms perform a survivability test, where they build a reference graph of all objects in the system. The GC traverses the graph, and any nodes (objects) that are not available are marked as unused and available for redistribution. The roots of the graph (the initial intersection points) include variables on the stack threads, static variables, and links stored in native code through the JNI. More details here: http://java.sun.com/developer/Books/performance/performance2/appendixa.pdf
Reference leaks are still possible. This applies to situations in which you hold a link to an object for longer than necessary. For instance:
public class Stack { private final Object[] stack = new Object[10]; private int top = 0; public void push(Object obj) {stack[top++] = obj;} public Object pop() {return stack[top--]; } }
Ignoring the possibility of overflow / overflow, after calling Stack.pop (), the member variable of the array still has a reference to the returned object. This will prevent this garbage collection until the surrounding instance of Stack is no longer referenced. This is one of the rare cases when it is necessary to set a variable to zero so that its memory can be fixed:
public Object pop() {Object ret = stack[top]; stack[top--] = null; return ret;}
source share