On Oct 16, 2012, at 10:27 AM, Daniel Kulp <[email protected]> wrote:
>> Hi Dan,
>> 
>> Thanks for your tip. Could you explain to me why do we remove the token when
>> it is null? I don't know much about ThreadLocal.
> 
> Internally, the "Thread" object keeps a map of the ThreadLocal object -> 
> Value.   If you set the value to null, it's still in the map with a null 
> value.  However, if you call remove, it removes the entire thing from the map 
> which helps make sure there are no threads holding onto anything that could 
> cause jar locking and such.
> 
> It's similar to HashMap behavior.    With a  HashMap, you can do:
> 
> hashMap.set("foo", null);
> or
> hashMap.remove("foo")
> 
> In both cases, a hashMap.get("foo") would return null.   However, the first 
> method would result in a size()==1 has there is a key/value pair in the map.  
> In the second case, the map is really empty.

I actually just realized why this is even more critical for Fediz.   With the 
ThreadLocal, the "key" in the map is the actual ThreadLocal object.   Thus, if 
it's not removed from the map entirely, if the ThreadLocal object holds 
something strongly, it can lock thing.     In many cases, this isn't super 
critical as ThreadLocal.class is loaded by the system classloader so if the 
value is null, it doesn't really "leak" anything other than a space in the map.

However, in Fediz, we're doing:
    private static final ThreadLocal<Element> TLS = 
        new ThreadLocal<Element>() {
        };

The { };   on the new ThreadLocal is causing an anonymous subclass of 
ThreadLocal to be created.   That is then loaded by the Fediz class loader.   
If that thread local is left in the map, it can lock the class loader used to 
load all the Fediz stuff and thus cause perm gen leaks and such.    Thus, I'd 
recommend:

1) Make sure we call remove() when appropriate

2) Remove the  { }; from the above to make it not be an anonymous class.


Dan






-- 
Daniel Kulp
[email protected] - http://dankulp.com/blog
Talend Community Coder - http://coders.talend.com

Reply via email to