Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a ThreadLocal has been initialized without actually doing that?

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.

like image 697
Christian Schlichtherle Avatar asked Jul 14 '12 13:07

Christian Schlichtherle


4 Answers

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.

  • do no override initialValue, ever - you are just asking for trouble, just forget it exists.
  • do not store non-system/non-bootstap classes in the ThreadLocal unless you do threadLocal.set(xxx); try{...process...}finally{threadLocal.set(null);}
  • if you still override initialValue, use threadLocal.remove() not threadLocal.set(null)
  • or use 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'd

I 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.

like image 102
bestsss Avatar answered Oct 18 '22 07:10

bestsss


Thoughts:

  • if ThreadLocal.get is called, the value is initialized.
  • If you don't want it initialized, you don't need the value stored (at all, ever)
  • If you want to avoid the initialize, it seems the place to start is by overriding get, not initialValue.
  • taking a different track - do you really need to inherit ThreadLocal as opposed to containment?
like image 20
Richard Sitze Avatar answered Oct 18 '22 09:10

Richard Sitze


One of the few possible ways of doing this would involve reflection as ThreadLocal does not have an API that lets you know whether the value has been initialized.

It is certainly possible to "code" it using reflection. However, all the usual caveat applies. Your reflection code would be highly dependent on the implementation details of java.lang.ThreadLocal and its non-public members. The moment the JDK vendors change the implementation your code would break.

like image 1
sjlee Avatar answered Oct 18 '22 07:10

sjlee


I am confused by your initial question. Is the ThreadLocal one that you are creating or it is already provided by someone else API?

If you are making the ThreadLocal, then I would assume you already know you have to override initialValue() so that you can provide the initial value.

In that case you can always track if that has been called and the value has been created.

I think something like this code below will do what you want:

MyThreadLocal<T> extends ThreadLocal<T>{

   Map<Thread,Boolean> myThreadMap = new HashMap<Thread,Boolean>();

   protected T initialValue(){
         synchronized(myThreadMap){
               T value =  ... your code to create initial value
               myThreadMap.put(Thread.currentThread(),true);
               return T;
         }
   }

   public boolean containsThreadValues(){
          synchronized(myThreadMap){
                 return myThreadMap.isEmpty();
          }
   }

   public boolean isInitializedForThisThread(){
         synchronized(myThreadMap){
                 return myThreadMap.get(Thread.currentThread())==true;
         }
   }


}

The myThreadMap will always contain old keys, even for dead threads. If you want old keys purged, then replace it with a WeakHashMap. Then the keys will be removed as the Threads that once used the ThreadLocal pass away.

like image 1
The Coordinator Avatar answered Oct 18 '22 07:10

The Coordinator