Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoCloseable and garbage collection relation

So I've read all about the autocloseable interface and try with resources, but that makes me wonder:

What happens if I do not(forgot) to wrap a class which implements AutoCloseable with a try with resources in a code which uses that class, but that class does take resources from the OS? While there is no guarantee on when JVM will decide it is time to call its garbage collector, when it does, will it call the close() method?

If not,is this where I will miss C++'s destructor? :) Is there a similar way to make sure, from within that class's code and not the user's code, that once the object should be released (for example out of scope) it will release all the OS resources it has taken?

like image 447
Yoni Keren Avatar asked May 20 '16 10:05

Yoni Keren


2 Answers

Depends on the class. Some do implement the finalize() method which is called when the GC collects the object, and do call close();, but it's not guaranteed.

Note that although you might think "yeehaw, Java does have destructors!" it's not the same thing, and you're not advised to start implementing finalize() in your own classes (I can't remember writing one in all my 16 years of Java programming).

You've already made the mistake when you've forgotten to close your resources, so fix that instead. With AutoCloseable it's a lot more convenient than it used to be too.

like image 172
Kayaman Avatar answered Oct 02 '22 09:10

Kayaman


You don't need to add any such documentation. Just make it Closeable or Autocloseable and everybody will know. At most, add a short comment "Don't forget to call close()" to a method/constructor used for obtaining an instance.

If not,is this where I will miss C++'s destructor?

For sure, you'll miss them. There's no real replacement in Java. finalize() and friends are rather unusable. Before the GC kicks in, you may long have run out of resources (file descriptors or alike).

You may use finalize() or alike for printing a warning. If the object gets GC'ed without having been closed before, it's a resource leak.

There are static analysis tools which flag non-closed resources. No idea, if they work with custom objects, but I'd bet that they look at all classes implementing (auto-)closeable.

like image 29
maaartinus Avatar answered Oct 02 '22 10:10

maaartinus