What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error?

This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception. Two important types of OutOfMemoryError are often encountered

  • lang.OutOfMemoryError: Java heap space
    • The quick solution is to add these flags to JVM command line when Java runtime is started:
      • -Xms1024m -Xmx1024m
    • lang.OutOfMemoryError: PermGen space
      • The solution is to add these flags to JVM command line when Java runtime is started:
        • -XX:+CMSClassUnloadingEnabled
        • -XX:+CMSPermGenSweepingEnabled

Long Term Solution: Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks. You can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place.