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.

A New Try-with-resources Improvement in JDK 9

| Java Language| 1,256 views | 2 Comments
About The Author
- Mite Mitreski works on custom enterprise application development and consultancy with primary focus on Java and JVM-based solutions. Currently he works as an engineer in Klarna on simplifying the buying experience. In the past he was involved in activities surrounding development groups in Macedonia where he was JUG Leader. Mite has a great passion for free and open source software, open data formats, and the open web. He is involved in the JCP and various other open source initiatives. At the moment he i is a community editor at Voxxed where he helps bring awesome content.

2 Comments

  • Luan
    Reply

    There is also this (most usual) syntax in Java 7/8:

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
    /**/
    }

    Since normally the reader won’t be used outside the scope of the try anyway 🙂
    But it is nice to see another options will be made available.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>