More concise try-with-resources statement now in JDK 9

joe darcy joe.darcy at oracle.com
Thu Jan 15 17:48:15 UTC 2015


Hello,

As part of milling Project Coin [1] in JDK 9, the try-with-resources 
statement has been improved. If you already have a resource as a final 
or effectively final variable, you can use that variable in the 
try-with-resources statement without declaring a new variable in the 
try-with-resources statement.

For example, given resource declarations like

         // A final resource
         final Resource resource1 = new Resource("resource1");
         // An effectively final resource
         Resource resource2 = new Resource("resource2");

the old way to write the code to manager these resources would be 
something like:

         // Original try-with-resources statement from JDK 7 or 8
         try (Resource r1 = resource1;
              Resource r2 = resource2) {
             // Use of resource1 and resource 2 through r1 and r2.
         }

while the new way can be just

         // New and improved try-with-resources statement in JDK 9
         try (resource1;
              resource2) {
             // Use of resource1 and resource 2.
         }

An initial pass [2] has been made over the java.base module in JDK 9 to 
update the JDK libraries to use this new language feature.

Please try out more more concise try-with-resources statement on your 
code and report any issues to compiler-dev.

Thanks,

-Joe

[1] http://openjdk.java.net/jeps/213

[2] https://bugs.openjdk.java.net/browse/JDK-8068948



More information about the jdk9-dev mailing list