Jinu P C Jinu P C - 2 months ago 6
Java Question

Why close() method is importent?

Why are we explicitly calling the close() method for closing the Connection, Statement and ResultSet?



Connection con = //getting Connection logic
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("my query");


Why we are explicitly close the objects by invoking thes close() methods

rs.close();
stmt.close();
con.close();


What are the benefits of close() method and what will happen when we close() the objects by invoking the close() method?

We can dereference the objects by using these statements. But why we do not use these statements. What is the difference between close() method and dereferencing the object?

stmt = null;
con = null;
rs = null;

Answer

What are the benefits of close() method and what will happen when we close() the objects by invoking the close() method?

Close frees resources before they run out.

We can dereference the objects by using these statements. But why we do not use these statements. What is the difference between close() method and dereferencing the object?

Your GC will only run when you run out of memory (or for CMS when you are running low). You could create one million Connections before a GC is triggered, but your database will either be long dead or will have rejected almost all of them to prevent being overloaded.