Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A New Try-with-resources Improvement in JDK 9

DZone's Guide to

A New Try-with-resources Improvement in JDK 9

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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/

Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

Topics:

Published at DZone with permission of Mite Mitreski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}