Wednesday, August 1, 2018

Java Code Bytes: Be Resourceful With Try-With-Resources

It is a very common that, while implementing a business case in Java, we have to deal with resources. In this context, a resource (such as a file or socket handle) is encapsulated in an object that we must close after they are used in order to release the resource. Traditionally, the onus was on the developer to close all the resources they created to avoid dependency collisions, generally in the following finally block. Failing to do so is not a compilation error, but it can easily lead to a leakage of resource. Though modern static code, analysis tools are smart enough to give you a hint, although not everyone uses them, and also, those alerts can be easily overlooked.

try-with-resources was first introduced in Java 7 and is a new way to handle (closing of) resources; it makes it easier dealing with resources by automatically taking care of the closing of resources in the correct order, which was used within a try-catch block.



from DZone.com Feed https://ift.tt/2vpOuDE

No comments:

Post a Comment