← All challenges

BreakIt · Java Elite Technical Sprint · advanced · 8 min

The Undying Web Request Siphon

An Enterprise application leaks database user connection context metrics across serverless web containers.

The setup

You utilize ThreadLocal to store tracking variables for thread contexts in an application server. The metrics map correctly, but over long deployment durations, memory footprints steadily climb until the application container crashes. Identify the leak.

The broken code

public class WebRequestContext {
    private static final ThreadLocal<byte[]> contextBuffer = new ThreadLocal<>();

    public void initializeRequest(byte[] rawPayload) {
        // TRAP: Setting reference parameters inside pooled worker execution vectors
        // maintains reference links to objects long after web tracking calls wrap up!
        contextBuffer.set(rawPayload);
        processContextLogic();
    }
    private void processContextLogic() { /* operational execution */ }
}

Hints

  1. Application servers reuse threads inside persistent thread pools.
  2. If a thread is kept alive indefinitely, when does its ThreadLocal map discard values?
  3. You must invoke the .remove() method within a try-finally framework to clear thread memory states upon transaction cleanup operations.

The fix

public class WebRequestContext {
    private static final ThreadLocal<byte[]> contextBuffer = new ThreadLocal<>();

    public void initializeRequest(byte[] rawPayload) {
        try {
            contextBuffer.set(rawPayload);
            processContextLogic();
        } finally {
            // Clean Fix: Cleanly strip contextual assignments when threads return to application pools
            contextBuffer.remove();
        }
    }
    private void processContextLogic() { /* operational execution */ }
}

Why it breaks

The Bug: ThreadLocal mappings link data objects to the active execution thread. Because application servers recycle threads using thread pools, un-removed parameters persist indefinitely, causing memory leaks across request boundaries.

Related challenges: The Undying String Intern Leak · The Unresponsive Shutdown Switch