Try with resources, first introduced in Java 7, is a Loan Pattern implementation baked in the
language which enables us to borrow a AutoCloseable resource, mess with it as we wish and in the
meanwhile, not to worry about freeing the resource; because it’s automatically being taken care of by
the compiler. Before this feature being rolled out, the common idiom to use a resource was kinda like the following:
Try with resources reduces the preceding code to:
There is no need to explicitly free the borrowed resource, which is nice, but the resource declaration
is a bit ugly and it’s even more uglier if we try to manage multiple resources:
The problem is, In Java 7, the resources to be managed by a try-with-resources must be fresh variables
declared like:
In Java 9, the try-with-resources statement refined in a way that it can accept final and effectively final
variables. So in Java 9 you can write: