This discussion is archived
1 Reply Latest reply: Mar 14, 2013 1:31 AM by jtahlborn RSS

threadlocal   without clear

user11138293 Newbie
Currently Being Moderated
I am using a thirdparty api , this api has a class which creates a threadlocal object and this class is widely used in this api, which I cannot change, unless I create my own jar.
the problem is this api does not clear the threadlocal here is the code of this class
public abstract class OsWorkflowContextHolder {

     /**
      * Holds the <code>OsWorkflowContext</code> on a per-thread basis.
      */
     private static ThreadLocal workflowContextHolder = new ThreadLocal() {
          protected Object initialValue() {
               return new OsWorkflowContext();
          }
     };

     /**
      * Gets the <code>OsWorkflowContext</code> for the current thread.
      */
     public static OsWorkflowContext getWorkflowContext() {
          return (OsWorkflowContext) workflowContextHolder.get();
     }

     /**
      * Binds a new <code>OsWorkflowContext</code> to the current thread.
      */
     public static void clearWorkflowContext() {
          workflowContextHolder.set(new OsWorkflowContext());
     }
}
clearWorkflowContext sets a new instance of OsWorkflowContext , when I use this class in web application the request which uses this class will end soon but the thread this object is bound to will live longer and will keep a reference to new OsWorkflowContext() and its not gc collected, is there any way I can overcome this without rewriting this with my own class?
  • 1. Re: threadlocal   without clear
    jtahlborn Expert
    Currently Being Moderated
    is OsWorkflowContext such a heavyweight object that it matters if one is lying around?

    what sort of answers are you expecting? some magic api to allow you to muck with existing code without recompiling it? you could always use reflection to access the ThreadLocal directly (nasty hack, of course). short of that, there's no other magic to be had.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points