Memory leak in j.l.ThreadLocal

Victor Polischuk victor2 at ukr.net
Sun Oct 27 05:19:16 UTC 2013


From: "Doug Lea" 26 October 2013, 21:15:36
> This could be considered a leak in that the spec/javadoc doesn't
> sufficiently emphasize that if a ThreadLocal includes a cyclic
> reference chain, then, in general, for a long-lived thread,
> you must call ThreadLocal.remove to clear it. (That is why
> method ThreadLocal.remove was introduced.)
> 
> As you (and Andrew) point out, this is a long-standing
> known issue. There is also a known solution, in fact only
> one form of solution known to work in general: Ephemerons,
> basically a new, special kind of WeakReference. (Try
> searching "java ephemeron" for discussion on various lists and forums).
> It would be swell if we had them. Maybe someone could open up
> a JDK9 JEP for them. But short of that, as Andrew implies,
> nothing is known to be better than what's there.
> 
> -Doug

Doug,

I apologize if I said something stupid but isn't correction of a wrong semantic of a frequently used part of JDK has more priority than high performance of a potentially unsafe code?

If I did not mess up with the idea reversing weak references then we will get small synchronization blocks only on setInitialValue() and remove(). I would definitely need a help from someone who knows how to measure performance of multi-threading components (have a couple of ideas who could it be) but my feelings are telling me that it is a small price.

My main point: if we slow down ThreadLocal a little but fix the issue with leaks it will benefit everyone who are working with huge lib stack (someone like me). I know that the situation we have currently with ThreadLocal is "the best" in terms of performance within JVM but my pain is located in the area of many custom libraries I have to use and which may or already have leaks. It is not easy to find memory leak and even afterwards it is way harder to fix if it occurs in 3rd-party lib. ThreadLocal is assumed stable core JavaAPI and many lib developers do not know of conditions in which their libraries will be used. In their turn lib users do not know details of implementation of a stack they are using. Unfortunately, it is nearly impossible to avoid leaks in the setup and ThreadLocal leaks one of them because (talking of PermGen/Metaspace leaks) it's absolutely unknown to the library when an application/plugin/module is going to be unloaded.

Sincerely Yours,
Victor Polischuk



More information about the core-libs-dev mailing list