How to Handle an Out of Memory Error in Java

When the Java Virtual Machine runs a Java program, it allocates memory for that program in two ways: a fixed-size segment containing all objects whose size was known at compilation time and a memory pool (called "heap") from which dynamic allocations will be serviced. If a program allocates enough dynamic objects to use up all the space on the heap, it will be terminated by the JVM with an "out of memory" error. You can prevent that error by instructing the JVM to allocate a larger heap at the beginning of the program's execution.

Instructions

    • 1

      Click "Start," and type "run" into the search box. Click "Run"; then type "cmd," and press "Enter." Click on the newly opened Command window to select it.

    • 2

      Change the current directory to the one containing your Java application (already compiled into ".class" files) by typing the following commands into the Command window:

      C:

      cd "C:\Users\paula\javaDev"

      Replace "C:\Users\paula\javaDev" by the application's folder. Replace "C:" by the corresponding drive letter. Press "Enter" at the end of each line.

    • 3

      Run your application by invoking the JVM with non-default heap size limits:

      java -Xmx1024MB progClass.class

      Replace "1024" by the maximum size the heap will be able to reach (in Megabytes; default is 64). This parameter should be set large enough (depending on your application) to prevent "out of memory" errors. Replace "progClass.class" by the class that defines the "main()" Java method. Press "Enter."

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured