Sunday, July 27, 2014

Why closing external resources after using it, If GC can take care?


It is strongly recommend that you always close the connection when you are finished using it so that the connection will be returned to the pool. Connections are a limited and relatively expensive resource. Any new connection you establish that has exactly the same connection string, will be able to reuse the connection from the pool. If we don't close a DB connection, we get something called a "connection leak" once threshold is reached.


Now come to the GC, GC Cannot guarantee of its execution, neither you can force JVM to run GC on your method (in case you don't close connection.) because GC is a demon thread and hence it has lowest priority. it may execute if it gets the CPU at that time.

So not closing connections and leaving it for GC may result in many problems like web pages hanging, slow page loads, and more.


Also, you should be careful while closing the connections or stream etc. because even though you are closing connection , sometimes it leads to resource leakage if not handled properly. 

Lets take an example: 

public static Properties loadProperties(String fileName) 
throws IOException { 
FileInputStream fis = new FileInputStream(fileName); 
Properties props = new Properties(); 
props.load(fis); 
fis.close(); 
return props; 


In the above example, 'fis' is closed but it still prone to resource leakage. 

How? 
>>It because, if any exception occurred at the call of "load" method only.. method will throw exception but will not release the resource properly. 

Correct way:::: 

public static Properties loadProperties(String fileName) 
throws IOException { 
FileInputStream fis= new FileInputStream(fileName); 
try { 
Properties props = new Properties(); 
props.load(fis); 
return props; 

finally { 
fis.close(); 



And JDK 7 Onwards, you don’t have to be worried about closing resources. You can use TRY,CATCH with resources functionality. 

static String readFirstLineFromFile(String path) throws IOException { 
try (BufferedReader br = 
new BufferedReader(new FileReader(path))) { 
return br.readLine(); 
// Use br…
 }  catch(Exception excp){….}


And one last point... 

Suppose you are using JDBC connection,statement and resultset. Then you should close all 3 resources not only connection. 

And the best way to handle this is>> 

public void someOperation() throws SQLException { 
Statement stmt= null; 
ResultSet rs= null; 
Connection conn= getConnection(); 
try { 
stmt= conn.createStatement(); 
rs= statement.executeQuery("SELECT * FROM EMP"); 
// Use RS 

finally { 
try { 
if (rs!= null) 
rs.close(); 

finally { 
try { 
if (stmt != null) 
stmt.close(); 

finally { 
conn.close(); 



}


Now one more question,  Why to close ResultSet and Statement ??
You must have heard about bad programming practices. So, It is a best programming practice to close ResultSet, Statement along with Connection.

How>> ?

If you are using JDBC connection and not closing ResultSet object it will be automatically closed. So, closing it in finally block will releases this ResultSet object immediately instead of waiting for this to happen when it is automatically closed. Closing ResultSet explicitly enables garbage collector to recollect memory as early as possible because ResultSet object may take lot of memory depending on query.

As per java doc of ResultSet object::

"A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results."

Also note that, you can get only one ResultSet object at a time from a Statement. So all execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

So, now Question is why statement should be closed?

As mentioned above the ResultSet will be closed automatically only if you close the Statement object. Not doing so will lead to resource leak.

This is the reason why JDBC API provided close() method for both ResultSet and Statement. These methods are not showpiece is'nt ?


Now, it’s totally depends on you whether you are writing a good quality code or not.

No comments:

Post a Comment

Thanks for your comments/Suggestions.