Memory Leakage

What is Memory leakage ?
Memory leaks often involve small amounts of memory resources, and you would probably not have problems with it. But when your application returns a java.lang.OutOfMemoryError, then your first and most likely suspect would be a memory leak.

Various Precautions required while programming 
  1. Release the session when it is no longer needed. Use the HttpSession.invalidate() to do this.
  2. Keep the time-out time low for each session.
  3. Store only the necessary data in your HttpSession.
  4. Avoid using string concatenation. Use StringBuffer’s append() method because the string is an unchangeable object while string concatenation creates a lot of unnecessary objects. A large number of temporary objects will slow down performance.
  5. If you are writing a query that is frequently executed, use PreparedStatement object rather than using Statement object. Why? PreparedStatement is precompiled while Statement is compiled every time your SQL statement is transmitted to the database.
  6. When using JDBC code, avoid using “*” when you write your query. Try to use the corresponding column name instead.
  7. If you are going to use stmt = con.prepareStatement(sql query) within a loop, then be sure to close it inside that particular loop. However its never recommended to iterate database connections in loop as its a very expensive operation.
  8. Be sure to close the Statement and ResultSet.
  9. Close the ResultSet, Connection, PreparedStatement, and Statement in the finally block or use try with resources.
  10. All the streams or resources should be closed after use.

Comments