Java Reference
In-Depth Information
ishbeforedestruction,theyremainintheheap.Eventually,theheapfillsandtheapplic-
ation halts.
Although this form of memory leakage is not a problem in Java, a related form of
leakageisproblematic:continuallycreatingobjectsandforgettingtoremoveevenone
referencetoeachobjectcausestheheaptofillupandtheapplicationtoeventuallycome
to a halt. This form of memory leakage typically occurs in the context of collections
(object-baseddatastructuresthatstoreobjects),andisamajorproblemforapplications
thatrunforlengthyperiodsoftime—awebserverisoneexample.Forshorter-livedap-
plications, you will normally not notice this form of memory leakage.
Consider Listing 2-49 .
Listing 2-49. A memory-leaking stack
public class Stack
{
private Object[] elements;
private int top;
public Stack(int size)
{
elements = new Object[size];
top = -1; // indicate that stack is empty
}
public void push(Object o)
{
if (top+1 == elements.length)
{
System.out.println("stack is full");
return;
}
elements[++top] = o;
}
public Object pop()
{
if (top == -1)
{
System.out.println("stack is empty");
return null;
 
Search WWH ::




Custom Search