A New Try-with-resources Improvement in JDK 9

The JEP 213 - Milling Project Coin is a follow up to the Project Coin additions to Java 7. Note, as the JEP states, this isn't a Project Coin 2.0. It's more of an attempt at smoothing the "rough edges" that came along with these additions. Just as a reminder - with the original Project Coin, among other things, we got:
  • Strings in switch
  • Binary integral literals and underscores in numeric literals
  • Multi-catch and more precise rethrow
  • Improved type inference for generic instance creation (diamond)
  • Try-with-resources statement
  • Simplified varargs method invocation
Try with resources has been a great simplification, especially when working with I/O code. The addition in JDK 9 is an improvement of the standard try-with-resources way of writing code. Previously in Java 7 and 8 we had;


BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Original try-with-resources statement from JDK 7 or 8
try (BufferedReader r1 = reader) {
// use buffered reader
} catch (IOException e) {
// ignoring exceptions because that is how I roll
}


which works just fine, but we still needed to declare a special variable in the try-with section. The cleaner and simpler way in JDK 9 is now;

// The JDK 9 way
try (reader) {
// use the reader
}catch (IOException e){
// ignoring exceptions because that is how I roll
}

This is more "natural" way of writing even though it 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 just final. You can play around with the new way already in the latest JDK 9 snapshot. More info available in Joe Darcy's Oracle Weblog post and the related  JDK bug report.

 Originally published on https://www.voxxed.com/blog/2015/01/new-try-resources-improvement-jdk-9/

Popular Posts