Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant example shows a leaking vector object. This quickly exhausts the heap space as the programmer has mistakenly written the condition for removing the vector element as n>0 instead of n>=0. As a result, in every iteration the method leaks one vector element.

Code Block
bgColor#FFCCCC
import java.util.Vector;
import java.io.IOException;

public class Leak {
  static Vector vector = new Vector();
  public void leakingVector(int count) { 	
    for (int n=0; n<count; n++) {
      vector.add(Integer.toString(n));
    }
    for (int n=count-1; n>0; n--) { //free the memory
      vector.removeElementAt(n);
    }	
  }

  public static void main(String[] args) throws IOException {
    Leak le = new Leak();
    int i = 1;
    while(true) {
      System.out.println("Iteration: " + i);
      le.leakingVector(1);
      i++;
    }
  }
}

...