← All challenges

BreakIt · Java Elite Technical Sprint · beginner · 4 min

The Ghost File Descriptor Leak

An automated document processor exhausts system storage handles, failing on large batch file imports.

The setup

You write an asset indexing utility designed to read file input data arrays consecutively. Even though you explicitly close file handlers at the end of the logic loop, the application throws a 'Too many open files' exception under heavy usage. Resolve the resource leak.

The broken code

import java.io.*;

public class FileIndexer {
    public void processDataFile(String targetPath) throws IOException {
        // TRAP: Traditional nested error initialization pathways risk bypass tracking loops
        // if system resource allocation faults trigger exceptions prior to execution wrappers!
        BufferedReader dataReader = new BufferedReader(new FileReader(targetPath));
        String inputLine = dataReader.readLine();
        System.out.println("Read payload index marker: " + inputLine);
        dataReader.close();
    }
}

Hints

  1. What happens if an unexpected exception fires on the readLine() step?
  2. The dataReader.close() instruction will be skipped, leaving the underlying operating system file handle unreleased.
  3. Refactor the instantiation flow to use Java 7+ try-with-resources syntax to guarantee automatic handle closure.

The fix

import java.io.*;

public class FileIndexer {
    public void processDataFile(String targetPath) throws IOException {
        // Clean Fix: Utilize target resource declaration blocks to enforce native safe breakdown cleanup sequences
        try (BufferedReader dataReader = new BufferedReader(new FileReader(targetPath))) {
            String inputLine = dataReader.readLine();
            System.out.println("Read payload index marker: " + inputLine);
        }
    }
}

Why it breaks

The Bug: If a runtime exception occurs prior to explicitly invoking close(), file handles remain open in the background. Over continuous processing loops, this behavior exhausts your operating system's file descriptor pools.

Related challenges: The Undying String Intern Leak · The Phantom Boxed Accumulator