Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


Members have full access to the forums. Advertisements are removed for registered users.

  • Re: Common Java Mistakes

    OutOfMemoryError: Java heap space
    Problem category: Runtime Error

    Diagnosis Difficulty: Medium-Hard
    Difficulty to Fix: Easy

    The JVM's default memory allocation is typically enough for a simple program. However, larger programs with memory intensive computation may result in throwing a java.lang.OutOfMemoryError exception during the execution of a program. A more fundamental analysis of memory usage and object allocation should be performed to confirm that the problem isn't an issue with the program design (such as keeping references to non-needed object), otherwise setting the maximum heap size may just cover up a more fundamental problem.

    Suggested fixes

    Increase the java virtual machine's default memory using the -Xmx option. By default, the maximum memory usage for the JVM is 64M. To increase this value, upon execution of the program pass the JVM the -Xmx* option, where * equals the requested memory (typically divisible by 64 until it reaches the gigabyte stage). For example, to run the program from the command line, call:

    java -Xmx512M myprogram

    One can increase this further (for example -Xmx1G) depending upon the available memory on the computer launching the program. For those using an IDE such as Eclipse, one should be able to pass the JVM arguments automatically. In Eclipse, go Run->Run Configurations->Arguments and enter the -Xmx option into the VM Arguments area.

    The problem gets a bit more difficult for deployment. Specifying the maximum memory for an executable jar is not possible without platform specific options (batch files, application bundles, etc...), however deploying applications via Java webstart allows the memory to be set via the max-heap-size parameter.

    Note: One can also set the minimum size of the JVM using the -Xms option in a similar way.
    This article was originally published in forum thread: Common Java Mistakes started by helloworld922 View original post