How to avoid Memory leak issue in Java
What is Memory Leak? How to determine if Memory Leak exists in a Java application?
|
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 <%@page session="false"%> 5. Try to use StringBuffer's append() method instead of string concatenation. 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. |
理解:
- 将session的过期时间尽可能设置的短一些
- 当session不需要的时候尽快释放
- session中存放的数据尽量的少
- 避免直接使用JSP中的Session对象
- 使用StringBuffer的append()方法而不是string的合并方法。String是一个不可变对象,如果我们调用它的合并方法,将会在堆中创建很多的临时对象,从而影响程序的表现 "SELECT id, name FROM t_customer whereMsoNormal"这句话将会创建4个string对象,而如果我们用StringBuffer的append()方法则只需要创建一个对象,因为StringBuffer对象是不可变的,可以不断地更改
- JDBC代码中尽量避免使用*,而使用列名在选择状态时
- 重复使用ResultSet和Statement对象前关闭他们
- 关闭掉ResultSet, Statement, PreparedStatement and Connection