Sunday, October 27, 2013

Memory Leaks

How to avoid memory leaks in java?
  • Use timeout time for session as low as possible.
  • Release the session when the same is no longer required, we can release the session using HttpSession.invalidate()
  • Try to store as less data as possible in the HttpSession.
  • Avoid creating HttpSession in JSP static pages using below page directive <%@ page session=”false” %>
  • Try to use StringBuffer’s append() method instead of string concatenation, String is an immutable object it will create many temporary objects in heap which result in poor performance.
  • In JDBC try to avoid “*” in select query
  • Try to use PrepareStatement object instead of statement object if the query need to be executed frequently as PrepareStatement is a precompiled SQL statement whereas statement is compiled each time the sql statement is sent to the database.
  • Close ResultSet and Statement before reusing those in finally block.

If the application runs with memory leaks for a long duration you will get the error java.lang.OutOfMemoryError.
  • Memory leak occur when an object of longer lifecycle has reference to the objects of a short life cycle. This prevents the objects with short life cycle being garbage collected.
  • Java collection classes like Hashtable, ArrayList etc maintain references to other objects. So having a long life cycle ArrayList pointing to many short life cycle objects can cause memory leaks.
  • Commonly used singleton design pattern can cause memory leaks. Singletons typically have a long life cycle. If a singleton has an ArrayList or a Hashtable then there is a potential for memory leaks.
  • Java programming language includes a finalize method that allows an object to free system resources, in other words, to clean up after itself. However using finalize doesn’t guarantee that a class will clean up resources expediently. A better approach for cleaning up resources involves the finally method and an explicit close statement. So freeing up the valuable resource in the finalize method or try block instead of finally block can cause memory leaks

No comments:

Post a Comment