Why are some some resources in Java not garbage collected and must be closed or autoclosed?

Christophe Roussy :

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.

Andy Turner :

why this cannot be automated in some way ?

Because, in general, a class can do anything: there is no easy way for the compiler to know that something was "opened", and thus should be "closed", because Java has no strong notion of ownership of values.

Even if you have a field which is of a type that needs closing, you can't easily guarantee that it won't be returned from a getter, say, to something else which is responsible for closing it.

The only really consistent way to indicate that instances of a class need closing is by implementing the AutoCloseable interface (or Closeable, or some other interface which extends it). If you're using these, IDEs may be able to provide warnings about leaked resources; but these are going to be on a best-effort basis.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=444486&siteId=1