Why and How to Manually Close Java Resource Objects
This article explains why Java developers must manually close resource objects such as streams and database connections, discusses the limitations of garbage collection, and presents best‑practice techniques like finally blocks, try‑with‑resources, and utility libraries for proper resource management.
This is the fourth article in the static code scanning series, following previous posts on PMD custom rules, detecting sensitive information in log files, and an introduction to FindBugs custom rules.
The author’s team has been researching Java resource‑closing rules, finding existing open‑source tools insufficient for their needs, and shares their insights on why manual closure is necessary.
Java resource objects include I/O streams, database connections, sockets, etc. If these are not closed promptly, they remain in memory, potentially leading to OutOfMemory errors.
Although Java has a garbage collector (GC) that reclaims memory of unreferenced objects, GC does not automatically close external resources like files or sockets, which must be released manually because they involve system‑level handles and may hold locks.
Java provides mechanisms such as finalizers and PhantomReference for automatic cleanup, but their execution timing is nondeterministic, so they should be a last resort.
Best practice is to close resources explicitly in a finally block, ensuring closure even when exceptions occur.
Since Java 1.7, the try‑with‑resources statement allows resources to be declared in the try clause, automatically invoking close() at the end of the block.
Third‑party libraries also offer convenience methods, for example Apache Commons IO’s IOUtils.closeQuietly(e) , which internally calls close() .
The article concludes with a reminder that this is the first part of the series and that future posts will explore special cases in resource‑closing detection.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.