3 ms·
Relying on GC to clean up finite resources such as open file descriptors is a risky idea because you can run out of file descriptors or other resources in betwe
by koreth1 6y ago
Relying on GC to clean up finite resources such as open file descriptors is a risky idea because you can run out of file descriptors or other resources in between GC invocations.
You absolutely can use AutoCloseable for things like logging. SLF4J, for example, provides MDC.putCloseable() which is designed to be used in a try-with-resources block.
As for how AutoCloseable works:
try (SomeAutoCloseableObject thing = SomeClass.someMethod()) {
...
}
is effectively just syntactic shorthand for
SomeAutoCloseableObject thing = SomeClass.someMethod();
try {
...
} finally {
thing.close();
}
That's it. There's no GC magic involved; it just calls "close" which is just an ordinary method that can have any arbitrary code in it. (I should add: try-with-resources isn't EXACTLY equivalent to the second example. But it's close enough for purposes of explanation.) The official docs explain it in more detail with more examples: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html https://docs.oracle.com/javase/tutorial/essential/exceptions...