简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM