Sam has posted 7 posts at DZone. View Full User Profile

Resource Clean Up in Java 1.7

03.25.2013
| 4148 views |
  • submit to reddit

It is was best practise until jdk1.6 to perform all cleaning activities such as closing all opened resources(e.g IO steams - FileInputStream/FileOutputStream) in finally block.

This non functional code can be delegated to JVM to take care of closing of all such resources. 

Java 1.7 has a feature/API to support automatic resource management as part of try/catch block. Closing resources in earlier version of Java and new version of java (1.7) is explained below with examples.

Handling clean up with older versions of Java

public static void performIO()throws IOException{
		
		FileInputStream is=null;
		FileOutputStream os=null;
		try{
			is=new FileInputStream(new File("readfile"));
			//.....
			os=new FileOutputStream(new File("writefile"));
			//.....
			
			
		}finally{
			if(is!=null) //there is a possibility of not getting instantiated.
				is.close();
			if(is!=null) //there is a possibility of not getting instantiated.
				os.close(); 
		}
	}

Handling clean up with Java 1.7
public static void performIO()throws IOException{	
	
		try(FileInputStream is=new FileInputStream(new File("readfile"));			
				FileOutputStream os=new FileOutputStream(new File("writefile"));
			){
			//.....
			//.....			
		}
	}

Whatever the objects are created inside try(), JVM will take care of close/cleanup, they need not to be closed manually.

You may be wondering, can this approach be extended to your custom resource intensive objects? Yes, it is quite possible, all you need to do make the class to implement AutoCloseable interface and include clean up stuff inside the close() method.

Hope this helps to adopt new approach in your new development projects.




Published at DZone with permission of its author, Sam Kyatham.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Robert Saulnier replied on Tue, 2013/03/26 - 7:01am

In the "Handling clean up with older versions of Java", you forgot to catch the IOExceptions in the finally block.

Sam Kyatham replied on Tue, 2013/03/26 - 8:44am in response to: Robert Saulnier

That's not required since the method throws IOException. Do you agree?

Anyhow these examples are just for demonstrating the subject. thank you.

Robert Saulnier replied on Tue, 2013/03/26 - 9:15am in response to: Sam Kyatham

I do not agree. If the try block throws an IOException and one of the close() methods in the finally throws an IOException, you will lose the initial IOException and the close IOException will be thrown from this method.

Also, you are closing two resources in the finally. What will happen if the first close throws an IOException? You will still have the second resource open.

Both close methods in the finally block must be in try-catch blocks.

Robert Saulnier replied on Tue, 2013/03/26 - 9:30am

This is what the performIO() should look like:

public static void performIO() throws IOException {
    InputStream in = null;
    OutputStream out = null;
        
    try {
        // use streams
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                logger.log(Level.WARNING, null, ex);
            }
        }
            
        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
               logger.log(Level.WARNING, null, ex);
            }
        }
    }
}

Sam Kyatham replied on Tue, 2013/03/26 - 10:29am in response to: Robert Saulnier

I see your point, that makes sense. Java7 greatly simplified all the creepy stuff, isn't it?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.