Versions Compared

Key

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

A Java OutofMemoryError occurs if infinite heap space is assumed, making the program crash. This error can be generated due to the following possible reasonsresult from:

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

Noncompliant Code Example (1)

This noncompliant code example places no upper bound bounds on the memory space required due to which to execute the program. Consequently, the program can easily exhaust the heap.A heap error will be generated if the heap continues to be populated even if there is no space available.

Code Block
bgColor#FFcccc
public class ShowHeapError {

  Vector<String> names = new Vector<String>();
  String newName=null;
  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(input);

  public void addNames(){
    do {
         // Adding unknown number of records to a list
         // the user can enter as much data as he wants and exhaust the heap
         System.out.print(" To quit, enter \"quit\"\nEnter record: ");
         try {
               newName = reader.readLine();
               if(!newName.equalsIgnoreCase("quit")){
                 // names are continued to be added without 
          // bothering about the size on the heap
                 names.addElement(newName);
        }
       }
 catch (IOException 	e) {
     } catch (IOException e) {
   			}// forward to handler 
      }
    
      System.out.println(newName);
      }while (!newName.equalsIgnoreCase("quit"));
    }

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

...

If the objects or data structures are large enough to potentially cause heap exhaustion, the programmer must consider using databases instead, to ensure that records are written to the disk in a timely fashion. Hence, this structure will never outgrow the heap..

To remedy the noncompliant code In the above example, the user can reuse a single long variable to store the input and write that value into a simple database containing a table User, with a field userID along with any other required fields. This will prevent prevents the heap from getting exhausted.

...

Code Block
bgColor#FFcccc
public class ShowHeapError {

  /* Assuming the heap size as 512mB512 MB (calculated as 1/4th of 2 GB RAM = 512mB512 MB)
   * Considering long values being entered (64 bits each, the max number of elements
   * would be 5122mB5122 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();
   }
}

...

Wiki Markup
The {{OutOfMemoryError}} can be avoided by making sure that there are no infinite loops, memory leaks or unnecessary object retention. If memory requirements are known ahead of time, the heap size in Java can be tailored to fit the requirements using the following runtime parameters \[[Java 06|AA. Java References#Java 06]\]:

...

java -Xms128m -Xmx512m ShowHeapError

Here we have set the initial heap size is set to 128MB 128 MB and the maximum heap size to 512MB512 MB.

This setting can be done changed either in the Java Control Panel or on the command line. It cannot be adjusted through the application itself.

...

Wiki Markup
According to \[[API 06|AA. Java References#API 06]\], Class {{ObjectInputStream}} documentation:

ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those the objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.

By design, only the first time an object is written, does it gets get reflected in the stream. Subsequent writes write a handle to the object into the stream. A table mapping the objects written to the stream to the corresponding handle is also maintained. Due to Because of this handle, references that may not persist during normal runs of the program are also retained. This can cause an OutOfMemoryError when streams remain open for extended durations.

...

If heap related issues arise, it is recommended that the ObjectOutputStream.reset() method be called so that references to previously written objects may be garbage collected.

Code Block
bgColor#ccccff
FileOutputStream fos = new FileOutputStream("data.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new Date());
oos.reset();  // Reset the Object-Handle table to its initial state
// ... 

Risk Assessment

It is difficult to identify code that can lead to a heap exhaustion since static analysis tools are currently unable to pinpoint violations. The heap size may also differ in different machinesAssuming that infinite heap space is available can result in denial of service.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC09- J

low

probable

medium

P4

L3

...