BIG
DATA

JAVA

Try with resources in Java 9

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 
java 9

Try with resources has been a great simplification, especially when working with I/O code. Introduced in Java 7, it allows us to declare resources to be used in a try block with the assurance that the resources will be closed when after execution of that block. The resources declared must implement the AutoCloseable interface.

Without this construct, Developer has to write lot of redundant and ugly code. If Developer forgets about closing resources properly, we will get Resource Leakage issues in our application.

Java 7 try-with-resources

This is how we use it from Java 7 and 8:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Original try-with-resources statement from JDK 7 or 8
try (BufferedReader r1 = reader) {
	// do somthing with buffered reader
} catch (IOException e) {
	//  exceptions handling
}

Above code works fine but we had to declare one more redundant variable in the try section. This looked ugly which is now simplified in Java 9. That is because we can’t use resource which is declared outside the try() block within it. If resource is already declared outside, we should re-refer it with local redundant variable.

Java 9 try-with-resources improvement

Java 9 make things simple. Lets see how it is done:

// The JDK 9 way
try (reader) {
	// do somthing with the reader
}catch (IOException e){
	// exceptions handling
}

This is simple and more natural way of writing even though in most use cases we don't need the resource outside the scope of the try block. The restriction is that the reader variable should be effectively final or declared final.

Note:An effectively final variable is the variable that never changed after initializing. That means the compiler finds it never appear in assignments outside its initialization.

So this is how Java 9 made try with resources simple by allowing effectively final variables to be used as resources in it.