Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Resource Clean Up in Java 1.7

DZone's Guide to

Resource Clean Up in Java 1.7

· Java Zone
Free Resource

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

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.




Discover when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}