What is Memory Leak?
Memory leak is a bug that mainly occurs when a program does not release the memory it has obtained for temporary use. In other words we can say 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.
1. Use time out time for the session as low as possible.
2. Release the session when the same is no longer required. We can release the session by using HttpSession.invalidate().
3. Try to store as less data as possible in the HttpSession.
4. Avoid creating HttpSession in jsp page by default by using the page directive
5. Try to use StringBuffer’s append() method instead of string concatenation.
String is an immutable object and if we use string concatenation, it will unnecessarily create many temporary objects on heap which results in poor performance.
For ex. if we write String query = “SELECT id, name FROM t_customer whereMsoNormal” style=”margin-bottom: 0.0001pt;”> it will create 4 String Objects. But if we write the same query using StringBuffer’s append() it will create only one object as StringBuffer is mutable i.e. can be modified over and over again.
6. In JDBC code, While writting the query try to avoid “*”. It is a good practice to use column name in select statement.
7. Try to use PreparedStatement object instead of Statement object if the query need to be executed frequently as PreparedStatement is a precompiled SQL statement where as Statement is compiled each time the Sql statement is sent to the database.
8. Try to close the ResultSet and Statement before reusing those.
9. If we use stmt = con.prepareStatement(sql query) inside loop, we should close it in the loop.
10. Try to close ResultSet, Statement, PreparedStatement and Connection in finally block.