2 Replies Latest reply: Jul 12, 2007 3:54 PM by jschellSomeoneStoleMyAlias RSS

    ThreadLocal and ClassLoaders

    807605
      Does TheadLocal work across classes loaded by different class loaders?

      I have a web application with a Filter, a JSP page, and a custom driver and use ThreadLocal object to keep track of session. Filter calls ThreadLocal.set() method to set session value; while as custom driver calls ThreadLocal.get() method to get session value.

      The problem is that when the thread is running through cursom driver, ThreadLocal.get() returns null even though the Filter has properly called the method ThreadLocal.set() for the same thread.

      I narrowed down the problem to the fact that one class loader is loading Filter and JSP servlet; while as another class loader is loading my custom driver. If I change the configuration to use a single class loader to load everything then ThreadLocal.get() in custom driver returns valid value.

      Any options to work around this?
        • 1. Re: ThreadLocal and ClassLoaders
          807605
          Servlet engines use a heirarchy of classloader. It's nothing specific to ThreadLocal, it's more likely that there is more than on copy of the class in whose static variables it lives.

          The trick is to put the class in the common libraries area of the web host so that the same copy is shared accross webapps.
          • 2. Re: ThreadLocal and ClassLoaders
            jschellSomeoneStoleMyAlias
            I have a web application with a Filter, a JSP page,
            and a custom driver and use ThreadLocal object to
            keep track of session. Filter calls ThreadLocal.set()
            method to set session value; while as custom driver
            calls ThreadLocal.get() method to get session value.

            The problem is that when the thread is running
            through cursom driver, ThreadLocal.get() returns null
            even though the Filter has properly called the method
            ThreadLocal.set() for the same thread.

            I narrowed down the problem to the fact that one
            class loader is loading Filter and JSP servlet; while
            as another class loader is loading my custom driver.
            If I change the configuration to use a single class
            loader to load everything then ThreadLocal.get() in
            custom driver returns valid value.
            I suspect that you are passing in an instance variable (class from the class loader) And that is the cause of the problem, not ThreadLocal.

            You would have the same problem if you attempted that with any other interface.

            Use a class instance that lives outside the loaders.