Skip to content

fix: clear empty DefaultThreadContextMap ThreadLocal state - #4524

Open
abu-tahir-0 wants to merge 1 commit into
apache:2.xfrom
abu-tahir-0:fix/clear-empty-thread-context-2523
Open

abu-tahir-0 wants to merge 1 commit into
apache:2.xfrom
abu-tahir-0:fix/clear-empty-thread-context-2523

Conversation

@abu-tahir-0

@abu-tahir-0 abu-tahir-0 commented Nov 24, 2026 •

Copy link
Copy Markdown

Problem

DefaultThreadContextMap.remove() and removeAll() retain an empty backing array in a ThreadLocal after the final entry is removed. Long-lived threads keep that state alive unnecessarily.

Root cause

Both methods unconditionally replaced the ThreadLocal value with the copied map's backing array, even when the resulting immutable map was empty.

Solution

Remove the ThreadLocal entry when the resulting map is empty; otherwise retain the non-empty backing array. Add tests for single-key, multi-key, removeAll, partial removal, and repeated removal, plus the 2.x changelog entry.

Testing

  • JAVA_HOME=<Java 17> ./mvnw -pl log4j-api-test -am -Dtest=DefaultThreadContextMapTest -Dsurefire.failIfNoSpecifiedTests=false test — 20/20 passed, independently rerun.
  • Agent verification: 4 new tests failed before the fix; ThreadContextTest 14 passed; garbage-free map tests 9 passed in four executions.
  • Spotless, changelog validation, and git diff --check passed.
  • A complete log4j-api-test reactor run was also attempted: 961 tests ran, with 15 failures/errors confined to untouched stack-location, service-loader, and status-listener tests under the Windows/classes-directory setup (including the existing multi-release-JAR warning). The focused ThreadContext suite remains green. Full verify site was not run.

Fixes #2523

Removing the last key or all keys currently retains an empty backing
array in the ThreadLocal. Remove the ThreadLocal entry instead and cover
last-key, multi-key, and repeated removal paths.
@ramanathan1504 ramanathan1504 added api Affects the public API bug Incorrect, unexpected, or unintended behavior of existing code java Pull requests that update Java code port-done No further port needed: all required ports are merged, or none was needed labels Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Affects the public API bug Incorrect, unexpected, or unintended behavior of existing code java Pull requests that update Java code port-done No further port needed: all required ports are merged, or none was needed

Projects

Development

Successfully merging this pull request may close these issues.

Removing all keys from ThreadContextMap does not clear the ThreadLocal

2 participants