Fix Memory Leak in Java
Actions to prevent memory leak:
- When a reference variable is no longer in use, assign null value to it.
- Close DataInputStreams and JDBC Connections.
- Shutdown the threads after completion.
- Restrict using static classes and methods.
- Put less data on Sessions.
- Invalidate Sessions.
- Set short duration for timeout of sessions.
- 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.
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
- Or for On-demand, if you are using Java6, then use jmap.exe -dump:format=b,file=HeapDump.hprof <pid>
- Now load these .hprof heapdump onto eclipse Memory Analyzer Tool http://www.eclipse.org/mat/