How to avoid Memory leak issue in Java
What is Memory Leak?
Memory leak mainly occurs when a program does not release the memory it has obtained for temporary use, it is the condition where the available computer memory reduces gradually there by resulting in poor performance.
How to determine if Memory Leak exists in a Java application?
If the application throws java.lang.OutOfMemoryError or if the program takes more time to execute than is required normally then there could be a memory leak in the application. There are various third party tools to detect and fix memory leaks but it is always better to prevent one from happening
How to avoid Memory Leak in Java?
While coding if we take care of a few points we can avoid memory leak issue.
- Use time-out time for the session as low as possible.
- Release the session when the same is no longer required. We can release the session by using HttpSession.invalidate().
- Try to store as little data as possible in the HttpSession.
- Avoid creating HttpSession in the JSP page by default by using the page directive
- Try to use StringBuffer’s append() method instead of string concatenation.
The string is an immutable object and if we use string concatenation, it will unnecessarily create many temporary objects on the heap which results in poor performance. For ex. if we write String a = “java”+” – “+ “koder” +” – “+”.com”; it will create 4 String Objects. But if we write the same string using StringBuffer’s append() it will create only one object as StringBuffer is mutable i.e. can be modified over and over again.
- Avoid using “*” in the JDBC code. It is a good practice to use column name instead of * in the select statement.
- Try using PreparedStatement object instead of Statement object if the query needs to be executed frequently as PreparedStatement is a precompiled SQL statement whereas Statement is compiled each time the SQL statement is sent to the database.
- Close the ResultSet and Statement before reusing those.
- Use stmt = con.prepareStatement(sql query) inside loop, we should close it in the loop.
- Close ResultSet, Statement, PreparedStatement, and Connection in finally block.