threadlocal variables in a servlet

14,124

Solution 1

Short answer: Yes.
A bit longer one: This is how Spring does its magic. See RequestContextHolder (via DocJar).

Caution is needed though - you have to know when to invalidate the ThreadLocal, how to defer to other threads and how (not) to get tangled with a non-threadlocal context.

Or you could just use Spring...

Solution 2

I think they are global to all requests made with that specific thread only. Other threads get other copies of the thread-local data. This is the key point of thread-local storage: http://en.wikipedia.org/wiki/Thread-local_storage#Java.

Unless you check the appropriate option in the servlets config, the servlet container will use your servlet with multiple threads to handle requests in parallel. So effectively you would have separate data for each thread that's up serving clients.

If your WebApplication isn't distributed (runs on multiple Java Virtual Machines), you can use the ServletContext object to store shared data across requests and threads (be sure to do proper locking then).

Solution 3

Using ThreadLocal to store request scoped information has the potential to break if you use Servlet 3.0 Suspendable requests (or Jetty Continuations) Using those API's multiple threads process a single request.

Share:
14,124
user2427
Author by

user2427

Updated on June 24, 2022

Comments

  • user2427
    user2427 almost 2 years

    Are the threadlocals variables global to all the requests made to the servlet that owns the variables?

    I am using resin for the server.

    Thanks for awnser.

    I think I can make my self more clear.

    The specific Case:

    I want to:

    • initialize a static variable when the request starts the execution.
    • be able to query the value of the variable in the further executions of methods called from the servlet in a thread safety way until the request ends the execution
  • Julie
    Julie over 15 years
    Indeed. On a previous project, I stored a user's ticket in their session, and created a filter to transfer the ticket from the session to a thread local to make sure that a user's authentication state was always available to the thread processing the request.