Skip to content

[Bug] ThreadContext Leak in Log4j2Demo causing Thread Pollution #171

@QiuYucheng2003

Description

@QiuYucheng2003

Description

The Log4j2Demo.java class demonstrates unsafe usage of ThreadContext within a thread pool environment.

The Bug

In the createTask method (Line 38), ThreadContext.put("task", ...) is invoked inside a Runnable. However, there is no corresponding ThreadContext.remove("task") or clearMap() call at the end of the execution.

Impact

When the thread returns to the ExecutorService pool, it remains "dirty" with the task context value. Subsequent tasks reusing this thread will inherit this stale context data, leading to Log Context Pollution (incorrect data appearing in unrelated logs).

Location

File: Log4j2Demo.java
Method: createTask() -> run()
Line: 43 (Missing cleanup after put)

Proposed Fix

Wrap the business logic in a try...finally block to ensure context cleanup:

public void run() {
    ThreadContext.put("task", new Date().toString());
    try {
        logger.info("Log in Runnable!");
    } finally {
        ThreadContext.remove("task"); // Preventing leak
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions