Try With Resource
Introduced with Java 7, a try-with-resource provided a cleaner way to perform cleanup operations on resources. This was a very useful feature where you need not explicitly do a cleanup of resources (which implements an AutoClosable interface) but it was done automatically for us. This is critical in applications where we are dealing with resources such as Database, I/O Streams where not cleaning up the resources will be costly.
One limitation of pre-Java 9 try-with-resource was that it can perform cleanup operations only if the Resource was instantiated inside the try block.
For example (pseudo code):
// This will cleanup Resource
try(Resource myResource = new Resource()) {
resource.doSomething();
}
// The below will not work in pre-Java 9 but works in Java 9
Resource resource = new Resource();
try(resource) {
resource.doSomething();
}
Will the above feature be useful or complicate things depends on how this is used. Since the resource can be created elsewhere and passed on to this method or given via Dependency Injection, closing this can create more problems (as it lives outside the try block). So, this feature has to be used with Care.
Have a look at another interesting feature of Java 9 - Private methods in interfaces.
No comments:
Post a Comment