In my Java classes, I sometimes make use of a ThreadLocal
mainly as a means of avoiding unnecessary object creation:
If its any help I use a custom SPI (an interface) and the JDK ServiceLoader
. Then all of my various internal libraries (jars) that need to do unloading of threadlocals just follow the ServiceLoader pattern. So if a jar needs threadlocal cleanup it will automatically get picked if it has the appropriate /META-INF/services/interface.name
.
Then I do the unloading in a filter or listener (I had some issues with listeners but I can't recall what).
It would be ideal if the the JDK/JEE came with a standard SPI for clearing threadlocals.