How to avoid memory leak in JAVA?

devquora
devquora

Posted On: Jan 09, 2021

 

    Several ways to avoid memory leaks in Java are as follows:
  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. As much as possible, you should not create HttpSession on your JSP page. You can do this by using the page directive <%@page session=” false”%>.
  6. If you are writing a query that is frequently executed, use the PreparedStatement object rather than using the Statement object. Why? PreparedStatement is precompiled while Statement is compiled every time your SQL statement is transmitted to the database.
  7. When using JDBC code, avoid using “*” when you write your query. Try to use the corresponding column name instead.
  8. If you are going to use stmt = con.prepareStatement(SQL query) within a loop, then be sure to close it inside that particular loop.
  9. Be sure to close the Statement and ResultSet when you need to reuse these.
  10. Close the ResultSet, Connection, PreparedStatement, and Statement in the finally block.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    NIIT Technologies Java Interview Questions

    What is abstraction?

    Abstraction is basically used to separate the useless data from the essential ones. Only the important things that need to be shown to the users are only being exposed. Here in these issues, the users...

    NIIT Technologies Java Interview Questions

    What is the difference between left and right outer join?

    The difference between the left and right outer join is as follows:S. N. Left Join Outer Join1 A left outer join provides the table in the FROM clause whose all rows are returned....

    NIIT Technologies Java Interview Questions

    Explain how HashMap works?

    HashMap in Java works on hashing principles. Hashing is a process in which hash functions are used to link key and value in HashMap....