August 27, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Java 7 Language Changes in Project Coin, Page 2

  • June 16, 2011
  • By Sridhar MS
  • Send Email »
  • More Articles »

Java 7 Language Change #3: Try with Resource Statement

Prior to the release of JDK 7, Java programmers had to manually releasing the resources (such as database connections, file handlers, and so on) that they were using in the code segment. Many times it becomes tedious to manage these, and even more difficult when exceptions occur during the process. Analyzing/debugging such scenarios is a nightmare that developers still fear.

The following code is a classic example of how to use try with catch for a file I/O operation.

Listing 3: FileIO with try
import java.io.*; class FileIO { int readValue; FileInputStream fileInputStream; public static void main(String args[]) { FileIO fileIO = new FileIO(); fileIO.readFile(); } private void readFile() { try{ fileInputStream = new FileInputStream("FileIO.java"); while((readValue = fileInputStream.read()) != -1) System.out.print((char)readValue); }catch(IOException ioexception) { System.out.println("IOException occurred: "+ioexception.getMessage()); try{ if (fileInputStream != null) { fileInputStream.close(); } }catch(IOException ioe) { //do nothing } } } }

The FileInputStream instance is closed in the catch block. Please note the corresponding try/catch that is present in the catch block as well. In general this will not result in the stream closing if there is an exception and to resources being held up forever.

Listing 4 shows an improved version where the priority is given to the resources that are declared as part of the try block, and all exceptions (if any) are lowered in priority.

Listing 4: FileIO with try-with-resource
import java.io.*; class FileIO { int readValue; FileInputStream fileInputStream; public static void main(String args[]) { FileIO fileIO = new FileIO(); fileIO.readFile(); } private void readFile() { try(FileInputStream fileInputStream = new FileInputStream("FileIO.java")) { while((readValue = fileInputStream.read()) != -1) System.out.print((char)readValue); }catch(IOException ioexception) { //Only handle what is needed. Do not worry about resources System.out.println("IOException occurred: "+ioexception.getMessage()); } } }

Benefit from Project Coin

These Java language changes, although small in nature, deliver big improvements in code complexity and maintenance. As always, it will take time to get familiar with them but they address some pain points the Java community has faced for years.

Sridhar M S is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.


Tags: Java 7

Originally published on http://www.developer.com.

Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel