threadlocal variables in a servlet

user2427 picture user2427 · Nov 26, 2008 · Viewed 13.8k times · Source

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

Answer

Ran Biron picture Ran Biron · Dec 17, 2008

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