I want to test if a ThreadLocal has been initialized without actually initializing it. Of course, the code needs to be thread-safe. Ideally I want something like this:
class TestableThreadLocal<T> extends ThreadLocal<T> {
public boolean isInitialized() {
...
}
}
But how would I implement this method?
Edit: Motivation: I have subclassed a ThreadLocal to override initialValue(). However, I do not always need the initialization, in particular because it could cause a memory leak in multi-classloader environments. A simple test would help me write code to avoid the accidental initialization.
I tend to use simple rules to avoid classloader leaks, admittedly they are cumbersome but with some wrapping it’s not that bad. Yes, leaks are evil.
initialValue, ever – you are just asking for trouble, just forget it exists.threadLocal.set(xxx); try{...process...}finally{threadLocal.set(null);}threadLocal.remove()notthreadLocal.set(null)WeakReferene(i.e. ThreadLocal<WeakReference<Foo>>) for the value from a pool that keeps the hard references. It might look counter intuitive but once the pool is cleared the values disappear and the classes are free to be GC’dI realize the post is not a direct reply to your question, however there is no simple way to achieve what you wish and keep the leaks at bay.