ReviseAlgo Logo

Common Java Pitfalls

Resource Leaks

Prevent leaks of database connections, file handles, and memory through proper resource management.

Interview: Critical for high-performance systems engineering. Expect questions on try-with-resources, AutoCloseable contracts, and common Java memory leak patterns.

Last Updated: June 13, 2026 9 min read

Java handles heap object cleanup via Garbage Collection, but it does not manage external system resources (file descriptors, sockets, db connections). These must be closed explicitly to prevent operational leaks.

System Resources

Operating system level hooks (file handlers, network connections) that JVM garbage collectors cannot release on their own.

Try-With-Resources

A modern Java construct that guarantees automatic resource cleanup for any class implementing the AutoCloseable interface.

Memory Leak

Objects that are no longer needed but remain reachable by the GC root, slowly consuming memory until OOM occurs.

Automatic Resource Management (ARM)

Before Java 7, resource cleanup was written inside finally blocks, leading to massive boilerplate and nested exception suppression issues.

The Try-with-resources statement solves this. Any class declaring implements AutoCloseable can be declared inside the try parameters. The JVM guarantees their close() method will run before leaving the block, even if exceptions occur.

Code Walkthrough

This class demonstrates try-with-resources with nested exception suppression features.

import java.io.*;

public class ResourceLeakDemo { public static void main(String[] args) { // Safe: automatically closes both reader and writer in reverse order of declaration try (BufferedReader br = new BufferedReader(new FileReader("input.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {

String line = br.readLine(); if (line != null) { bw.write(line); } } catch (IOException e) { System.out.println("Exception handled. Files closed safely."); } } }

Interview-Relevant Information

Q: What is exception suppression in Try-with-resources?
Answer: If the try block throws an exception, and subsequently the auto-generated close() method also throws an exception, the primary try block exception is thrown up the stack. The close exception is not lost; it is appended as a suppressed exception which can be inspected via e.getSuppressed().

Q: What are the common causes of Java Memory Leaks?
Answer: While GC is automatic, objects remain in memory if they are referenced by active roots. Common causes include:

  • Static Fields: Static references survive the class's runtime duration, keeping objects alive indefinitely.
  • Unclosed ThreadLocals: ThreadLocals survive as long as the Thread pool workers are alive, caching stale thread variables.
  • Improper equals() and hashCode(): Prevents HashMap from identifying duplicate additions, leading to unbounded map growth.

Quick Checklist

Does your resource implement AutoCloseable? Do you clean up ThreadLocal references after request execution? If yes, you avoid resource leaks.

Use Cases

Safely managing database connection lifecycles in high-load services.

Reading filesystem streams reliably under strict OS descriptor limits.

Common Mistakes

Declaring resources outside try-with-resource headers, relying on manual closes in non-finally blocks.

Failing to remove request states from ThreadLocal variables in server environments, leaking data across user sessions.