Understanding OutOfMemoryError Exception

The java.lang.OutOfMemoryError means that your program needs more memory than your Java Virtual Machine (JVM) allowed it to use!!! This is a runtime error in Java which occurs when you allocate a new object in your application over a period of time continuously and the Garbage Collector (GC) cannot make space available to accommodate a new object, and the heap cannot be expanded further, which resulted this error.

Possible reasons:

  1. Improper configuration (not allocating sufficient memory).
  2. Application is unintentionally holding references to objects and this prevents the objects from being garbage collected.
  3. Applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time. If the finalizer thread cannot keep up, with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.
Therefore you pretty much have the following options:
  1. Find the root cause of memory leaks with help of profiling tools like MAT, Visual VM , jconsole etc. Once you find the root cause, You can fix this memory leaks.
  2. Optimize your code so that it needs less memory, using less big data structures and getting rid of objects that are not any more used at some point in your program.
  3. Increase the default memory your program is allowed to use using the -Xmx option (for instance for 1024 MB: -Xmx1024m). By default, the values are based on the JRE version and system configuration.

Increasing the heap size is a bad solution, 100% temporary, because you will hit the same issue if you get several parallel requests or when you try to process a bigger file.

To avoid these issues, write high performance code:
  1. Use local variables wherever possible.
  2. Release those objects which you think shall not be needed further.
  3. Make sure you select the correct object (ex: Selection between String, StringBuffer and StringBuilder).
  4. Avoid creation of objects in your loop each time.
  5. Use a good code system for your program(ex: Using static variables Vs. non static variables).
  6. Try to use caches.
  7. Try to move with Multy Threading.