[ 
https://issues.apache.org/jira/browse/LOG4J2-1142?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=14940632#comment-14940632
 ] 

Remko Popma commented on LOG4J2-1142:
-------------------------------------

I confirmed (in Tomcat 7.0.50) that it made no difference whether the 
ThreadLocal field static or non-static in AbstractStringLayout; both generated 
the warning

{quote}
SEVERE: The web application [/threadlocal] created a ThreadLocal with key of 
type [org.apache.logging.log4j.core.layout.AbstractStringLayout$1] (value 
[org.apache.logging.log4j.core.layout.AbstractStringLayout$1@5339ea5b]) and a 
value of type [java.lang.StringBuilder] (value []) but failed to remove it when 
the web application was stopped. Threads are going to be renewed over time to 
try and avoid a probable memory leak.
{quote}

The warning goes away if we avoid creating an inner class, so instead of this:

{code}
// tomcat generates warning
protected static final ThreadLocal<StringBuilder> strBuilder = new 
ThreadLocal<StringBuilder>(){
    @Override
    protected StringBuilder initialValue() {
        return new StringBuilder(DEFAULT_STRING_BUILDER_SIZE);
    }
};
{code}

Use this:
{code}
// no warning
protected static final ThreadLocal<StringBuilder> strBuilder = new 
ThreadLocal<StringBuilder>();
{code}

I will look at the pool next.

> ThreadLocals in Layout implementations should be non-static to prevent memory 
> leaks in web containers
> -----------------------------------------------------------------------------------------------------
>
>                 Key: LOG4J2-1142
>                 URL: https://issues.apache.org/jira/browse/LOG4J2-1142
>             Project: Log4j 2
>          Issue Type: Improvement
>          Components: Layouts
>    Affects Versions: 2.4
>            Reporter: Dmitri Blinov
>            Assignee: Remko Popma
>             Fix For: 2.4.1
>
>         Attachments: LOG4J2-1142.patch
>
>
> As discussed in LOG4J2-1125, storing ThreadLocal<StringBuilder> in a static 
> field may not interact well with the thread pools and class loaders of some 
> web containers and may result in memory leaks, especially in older web 
> containers.



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)

---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-dev-unsubscr...@logging.apache.org
For additional commands, e-mail: log4j-dev-h...@logging.apache.org

Reply via email to