Java 9 (Part 4): Trying Try-with-Resources: First Look

This is part 4 of the java 9 series. While in part 3 we covered interfaces and the private methods that were added to them, in part 4 we see that try-with-resoures was enhanced, or we might say even fixed. Try-with-resources, which was introduced back in java 7, is a concept which helps developer close resources which are not using anymore, such as database connectionfile streams, etc. Let’s see how try-with-resources behaved in java 7 and now in java 9.

Image title

Step 1: Pre-Java 7 Try-with-Resources

Try-with-Resources, prior to Java 9, meant that instead of just calling a piece of code which opens up a resource like:

InputStream input = null;
try {
    // open some resource note we are inside the try block.
    input = new FileInputStream("somefile");
} finally {
    // Hey don't forget to close them! we are not java 7 yet!
    if (input != null)
        input.close();
}

As you see in the above example we have used a standard try-and-finally.

Step 2: Try-with-Resources From Java 7 and On 

In Java 7, we can put the opening of the stream itself inside the try() block note that now try has brackets - try()

So we use it as:

try(FileInputStream input = new FileInputStream("somefile")) {

}


Where is the close() you ask? Java will take care of that. After all, it’s try with resources.

Step 3: Try-with-Resources From Java 9 and On

If we have multiple resources and we are using them and we want try-with-resources to close them all, now with Java 9, it's possible even without introducing a new variable- if our resource is already with the final keyword, that is.

final Resource resource1 = new Resource("resource1");
Resource resource2 = new Resource("resource2");

try(resource1; resource2 ...) { // couldn't do that before java 9
  // do something with the resources.
}

However, with Java 9 we can:

final Resource resource1 = new Resource("resource1");
Resource resource2 = new Resource("resource2");

try(resources1, resources2) { // possible with java 9
}

In Part 1 of this series we covered Java 9 modules, in Part 2, JShell, and then we went on to super interfaces in Part 3. In this Part 4, we saw that try-with-resources was greatly enhanced to allow us to refer to multiple seamlessly without the need to define any intermediate variable. So, you just try-with-resources seamlessly for multiple resources!

 

 

 

 

Top