ppkarwasz commented on issue #3819:
URL: 
https://github.com/apache/logging-log4j2/issues/3819#issuecomment-3069173172

   > I don't know if Logback has support for something similar to this pooling 
that can help in similar cases.
   
   Logback does **not** support object pooling in this context—it only uses 
`ThreadLocal`s for MDC. This means that the use of `LoggingEventBuilder` 
(introduced in SLF4J 2.0) is slightly more memory-intensive than traditional 
logging calls.
   
   > Regarding the last sentence, I think that in this case the problem is more 
about who "owns" the threads for which the ThreadLocal are allocating values 
rather than which classloader loaded the classes.
   
   You're absolutely right—the thread's ownership also plays a critical role 
here:
   
   - For threads created and managed by the application itself, this is 
generally not a problem. Those threads will be terminated when the application 
shuts down, releasing any associated `ThreadLocal` data.
   - Tomcat’s request-handling threads (e.g., `http-nio-*`) are also not a 
major concern, since Tomcat recycles and replaces them over time.
   - The real risk comes from **long-lived container threads**, such as 
`Catalina-utility-*` or `catalina-start-stop-*`. If logging happens on these 
threads during application shutdown (a common case), and thread-local values 
refer to classes from the application, it can cause permanent classloader 
leaks—because those threads persist beyond the application lifecycle.
   
   It’s also worth noting that even Log4j Core **intentionally ignores** 
`log4j2.enableThreadlocals` in some edge cases—specifically when only JDK 
classes are stored in the `ThreadLocal`. A good example is the [direct encoders 
feature](https://logging.apache.org/log4j/2.x/manual/systemproperties.html#log4j2.enableDirectEncoders),
 where no classloader-related leaks can occur.
   
   > Given that, I would even more lean toward the minimalistic solution, where 
the value `Constants.ENABLE_THREADLOCALS` actually controls if the ThreadLocal 
is used or not. In that way, scenarios that could leverage on pooling and 
reusing objects will benefit of the reduced generation of memory garbage.
   
   I submitted #3824, which ensures that access to the `ThreadLocal` is 
**properly** gated by `Constants.ENABLE_THREADLOCALS`.
   
   Feel free to take a look and review it!
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscr...@logging.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to