How to avoid Memory leak issue in Java

 

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

    <%@page session="false"%>

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.

理解:

  1. 将session的过期时间尽可能设置的短一些
  2. 当session不需要的时候尽快释放
  3. session中存放的数据尽量的少
  4. 避免直接使用JSP中的Session对象
  5. 使用StringBuffer的append()方法而不是string的合并方法。String是一个不可变对象,如果我们调用它的合并方法,将会在堆中创建很多的临时对象,从而影响程序的表现 "SELECT id, name FROM   t_customer whereMsoNormal"这句话将会创建4个string对象,而如果我们用StringBuffer的append()方法则只需要创建一个对象,因为StringBuffer对象是不可变的,可以不断地更改
  6. JDBC代码中尽量避免使用*,而使用列名在选择状态时
  7. 重复使用ResultSet和Statement对象前关闭他们
  8. 关闭掉ResultSet, Statement, PreparedStatement and Connection

 

 

 

 

       

你可能感兴趣的:(How to avoid Memory leak issue in Java)