{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner
java,* java * performance * serialization * xml,java 1.7,resource cleanup

Resource Clean Up in Java 1.7

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;
			is=new FileInputStream(new File("readfile"));
			os=new FileOutputStream(new File("writefile"));
			if(is!=null) //there is a possibility of not getting instantiated.
			if(is!=null) //there is a possibility of not getting instantiated.

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.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks