Thursday, July 5

Fix Memory Leak in Java


Fix Memory Leak in Java

Actions to prevent memory leak:

  1. When a reference variable is no longer in use, assign null value to it.
  2. Close DataInputStreams and JDBC Connections.
  3. Shutdown the threads after completion.
  4. Restrict using static classes and methods.
  5. Put less data on Sessions.
  6. Invalidate Sessions.
  7. Set short duration for timeout of sessions.
  8. Avoid using String for concatenation instead use StringBuffer.

How do we know memory leak is happening?

Getting OutOfMemoryError (OOM) is a sign of possible memory leak. The other way is by checking the used JVM heap size. If the heap size is rising with time then clearly you have memory leak.

memory leak java heapdump graph


Debugging memory leak

  • In Tomcat, open Catalina.bat file, set CATALINA_OPTS with XX:+HeapDumpOnOutOfMemoryError
set CATALINA_OPTS=%CATALINA_OPTS% -XX:+HeapDumpOnOutOfMemoryError


  • Now a heap dump is written on the first Out Of Memory Error into %CATALINA_HOME%\bin as java_pid<pid>.hprof
memory leak java heapdump file


  • Or for On-demand, if you are using Java6, then use jmap.exe -dump:format=b,file=HeapDump.hprof  <pid>  
memory leak java jmap




No comments:

Post a Comment