Versions Compared

Key

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

A Java OutofMemoryError occurs if infinite the program attempts to use more heap space is assumedthan is available, even after garbage collection. This error can result from:

  • A memory leak
  • An infinite loop
  • The program requires more memory than what is available by default on the heap
  • Incorrect implementation of common data structures (hash tables, vectors and so on)
  • Unbound deserialization
  • Upon writing a large number of objects to an ObjectOutputStream

...

Code Block
bgColor#FFcccc
public class ShowHeapError {

  /* Assuming the heap size as 512 MB (calculated as 1/4th of 2 GB RAM = 512 MB)
   * Considering long values being entered (64 bits each, the max number of elements
   * would be 5122512 MB/64bits = 67108864)
   */
   Vector<Long> names = new Vector<Long>(67108865);
   long newID=0L;
   int count = 67108865;
   int i = 0;
   InputStreamReader input = new InputStreamReader(System.in);
   Scanner reader = new Scanner(input);

   public void addNames(){
     do{
       /* Adding unknown number of records to a list
        * the user can enter more number of IDs than what the heap can support and 
        * exhaust the heap. Assume that the record ID is a 64 bit long value
       */
       System.out.print(" To quit, enter -1\nEnter recordID: ");
       newID = reader.nextLong();
       //names are continued to be added without bothering about the size on the heap
       names.addElement(newID);
       System.out.println(newID);
       i++;

     }while (i<count || newID!=-1);
   }

   public static void main(String[] args) {
     ShowHeapError demo = new ShowHeapError();
     demo.addNames();
   }
}

...