Coding - Java Project

Java Application

Memory Leak

How to Detect Java Memory Leaks?

  • Use Eclipse memory leak warnings. or plugin Memory Analyzer.
  • Java Visual VM or jconsole, connect with JMX, provides memory and CPU profiling, heap dump analysis, memory leak detection, access to MBeans, and garbage collection.
  • Java Profilers, help you monitor different JVM parameters: object creation, thread execution, method execution and garbage collection.
  • Using heap dumps, allow you to see the number of instances open and how much space these instances take up.
  • If your app just crashes without returning an OutOfMemoryError message, you can check the fatal log error or the crash dump to see what went wrong.
  • JVM settings: enable verbose garbage collection.

    $JAVA_OPTS=“-DLauncher=PRIME -DinstanceID=1 -Xms1024M -Xmx23552M -XX:+UseLargePages -XX:PermSize=256M -XX:MaxPermSize=1286M -XX:+PrintGCDateStamps -verbose:gc -XX:+PrintGCDetails -Xloggc:\“gclog.txt\” -DloggerImplName=PclnLogger -Dcom.sun.management.jmxremote.port=4321 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false”;

How to Avoid Java Memory Leaks?

  1. Use reference objects to avoid memory leaks.
  2. Avoid memory leaks related to a WebApp classloader. (static fields)
  3. Other specific steps.
    • Release resources and sessions when it’s no longer need.
    • Use StringBuffer. A large number of temporary objects will slow down performance.
    • Use PreparedStatement object and parameterized sql.
    • Close stream, connection, statement in the finally block.
  4. Optimize your code to bath processing data.
  5. Even if you specify System.gc(), the garbage collector might not run until the memory runs low.

What to do with Memory Leaks?

  • Java heap space: Means that memory resources could not be allocated for a particular object in the Java heap. This can mean several things, including a memory leak, or the specified heap size is lower than what the application needs. It could also mean that your program is using a lot of finalizers.
  • PermGen space: This means that the permanent generation area is already full. This area is where the method and class objects are stored. You can easily correct this by increasing the space via -XX:MaxPermSize. (Removed from Java 8)
  • Requested array size exceeds VM limit: This means that the program is trying to assign an array that is > than the heap size. You might need to optimize your code and use batch or pagination.
  • Request <size> bytes for <reason>. Out of swap space?: This means that an allocation using the local heap did not succeed, or the native heap is close to being all used up.
  • <Reason> <stack trace> (Native method): This means that a native method was not allocated the required memory.

Reference Resources