Video in progress
Does the GC close a file or DB connection by itself?
No. The GC only returns heap memory; it knows nothing about OS resources (file descriptors, sockets, DB connections). You have to close them yourself with try-with-resources or close().
📖 Answer
This happened on one project: after a few hours the service crashed with Too many open files, while the heap was half empty. The cause was a Files.lines(path) stream that was never closed. Since the heap wasn't full, the GC wasn't in a hurry, and the descriptors kept piling up.
// wrong: the stream isn't closed
long count = Files.lines(path).count();
// correct
try (Stream<String> lines = Files.lines(path)) {
long count = lines.count();
}
The same goes for JDBC: if you don't close a Connection, it doesn't go back to the pool, and soon HikariCP says Connection is not available, request timed out.
Some classes have a Cleaner inside that tries to close the resource during GC. But that is only a safety net: when it runs is unknown. Don't rely on it.
Sign up to mark studied questions and save your progress.