Sunday, August 29, 2010

Java 7 Automatic Resource Management

One of the features in Java 7 is Automatic Resource Management. The idea was presented by Josh Bloch. The IO resources in Java need to close manually like FileInputStream, java.io.InputStream, OutputStream, Reader, Writer etc. The idea with this proposal is that it should not be the responsibility of the developer for disposing out these resources much like automatic garbage collection concept.

We usually write this kind of code for IO resources as below.

FileInputStream input = null;            
try {              
    input = new FileInputStream(configResource);               
    wfConfiguration = wfConfiguration.parseInputStream(input);           
} catch (IOException ioe) {               
      throw new RuntimeException(ioe);           
} finally {               
      if (input != null) {                   
           try {                       
             input.close();                   
           } catch (IOException ioe2) {                       
             throw new RuntimeException(ioe2);                   
           }               
      }           
}

The same code can be written in Java 7 as
FileInputStream input = null;            
try (input = new FileInputStream(configResource)) {         
      wfConfiguration = wfConfiguration.parseInputStream(input);     
} catch (IOException ioe) {               
      throw new RuntimeException(ioe);       
}

Hope you like the new syntax.

Project Coin: Updated ARM Spec

3 comments:

  1. This is something taken for c# and its in c# for years :P, in C# we implement IDisposable interface and then use that in the "using" block as the using block end the IDisposable method Dispose called automatically. So java please hurry-up , you are really very far behind C#. Even not sure that if java7 coming in September or not. Looks like JAVA honey-moon period is over :S .

    ReplyDelete
  2. Good Point. In Java world, usually these Syntactic sugars do not favor much. The same reason, you won’t find the automatic accessor methods like C# has. Usually these Syntactic sugars need to introduce at the expense of breaking the existing clients while Java is extremely careful in this.

    ReplyDelete
  3. And yes, Java 7 might be delay due to the add of new projects (lambda, Coin, Jigsaw) and the acquisition of Sun by Oracle.

    ReplyDelete