If you are lucky some of these classes implement AutoClosable but sometimes you just have to be careful and inspect the existing methods to notice that there is a close
, destroy
or shutdown
method (or what ever the author decided to name it).
This is a major source of resource leaks in Java.
I was discussing this with a colleague and wondered too: why can this not be automated in some way ?
In theory you can use finalize
for such cases, but it is not recommended. So why is there no way to just use some of those closable resources and let the GC autoclose them when the instance is no longer reachable without having to remember to explicitely write some close
handling code (like try ...) ?
Is this because the system may have been resource starved (File descriptors, ...) before the GC kicks in ?
NOTE: I use autoclose when possible and check my code for memory leaks using FindBugs (+ FB contrib), but still, I wonder ...
Also of interest (as discussed in the answers): deprecation of finalize.