Loitering

1116 ワード

public String pop() { // Remove item from top of stack.
    String item = a[--N];
    a[N] = null; // Avoid loitering (see text).
    if (N > 0 && N == a.length / 4)
        resize(a.length / 2);
    return item;
}

Java’s garbage collection policy is to reclaim the memory associated with any objects that can no longer be accessed. In our pop() implementations, the refer- ence to the popped item remains in the array. The item is effectively an orphan—it will be never be accessed again—but the Java garbage collector has no way to know this until it is overwritten. Even when the client is done with the item, the reference in the array may keep it alive. This condition (holding a reference to an item that is no longer needed) is known as loitering. In this case, loitering is easy to avoid, by setting the array entry corresponding to the popped item to null , thus overwriting the unused refer- ence and making it possible for the system to reclaim the memory associated with the popped item when the client is finished with it.
 
Quoted from Algorithms, 4e.