close
will in most cases eventually be called automatically by the GC through the finalize
method (any class can have such finalize
that is called by the GC when destroying the object; for Closable
types that hold resources it will generally be implemented to call close
). The issue of course is that you just don't have control over when this happens (if ever). It could be 10 sec or 10 min from when you stopped needing the object, still using up whatever resource was allocated. So it's good style to clean up your resource handles once you don't need them anymore.
Also, since Java 7 you can actually do this:
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
And close
will be called automatically at the end of the try block.
See the documentation for more details.
And finally, to the why there is Closable
and things that need explicit closing in the first place, this is for resources that are not directly managed by the JVM and can hence also not automatically be reclaimed by GC. Such resources are for instances files, sockets or audio output.