InheritableThreadLocal and Tomcat
Java - 1 Comment » - Posted on May, 8 at 1:18 am
InheritableThreadLocal does not work with tomcat as tomcat thread pool does not clear the thread local contacts after a request has been executed. This results in no good way to share information information between the parent and the child threads that are created using thread local variables.
One way to solve this problem is to maintain a reference to the parent thread by writing your own thread that is constructed by a thread factory.
-
import java.util.HashMap;
-
import java.util.Map;
-
public class ClassNeedingInheritableThreadLocal {
-
return inheritableThreadLocal.get(getThread());
-
}
-
inheritableThreadLocal.put(getThread(), context);
-
}
-
if(currentThread instanceof MyThread) {
-
currentThread=getParent((MyThread) currentThread);
-
}
-
return currentThread;
-
}
-
if(parent instanceof MyThread) {
-
return getParent((MyThread) parent);
-
} else {
-
return parent;
-
}
-
}
-
}
Create a executor service by using our thread factory
-
ExecutorService service=Executors.newFixedThreadPool(10, new MyThreadFactory());
Remember that you would need to clean up all the objects that were put in the thread local. This can be done with a filter or by using AOP.
Posted in Java | 1 Comment »
Hi Rajesh,
Thank you very much for your excellent article.
Your article helped me to avoid problems before they appear.
Do you know if this issue persists on recent versions of Tomcat?
Thanks very much.
Richard Gomes
M: 44(77)9955-6813
http://www.jquantlib.org/index.php/User:RichardGomes
twitter: frgomes
Jquantlib is a library for Quantitative Finance written in Java.
http://www.jquantlib.org/
twitter: jquantlib