Java 8 - Auto closure of resource stream

Java 8 at it's best! Yes and handles memory leaks scenarios very effectively.

Memory leaks scenarios should be handled by programmer very carefully and here java 8 comes to rescue for taking care some of scenario out of the box. 

Before I begin, let me quickly put short note on what is referred to as memory leak in a java application.

Memory leak is scenario in which garbage collector is not able to release objects. You would think what are these objects would be, yeah?!
so, such object are those objects which are created by the application and not in use by the application but are being referenced from the code! 
Yes, such objects eats up memory and hence leads to out of memory error because GC won't be able to release them because of their reference.


I will try to cover Memory Leak in detail on my other post, so for now, let's proceed with how java 8 handles few of the memory leak scenario out of the box.

Consider a scenario when you are reading large text file by opening a connection to URL and reading contents over inputstream.

Below code sample, leads to memory leak because buffered reader is never closed.




Java 8, comes to rescue and provides capability to auto closure of steams.
see the modified version of above code with java 8.








No comments: