0

In a webapp, I have a scenario where I need some kind of global context (Static like) for few variables, for the current thread only.

If there are 3 different concurrent users, then I expect three corresponding global context variable for the 3 separate threads/sessions.

Using a Static variable makes its scope global for all the threads.

Is there a way in which I can achieve this?

6
  • 2
    How about using session scope? docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html Commented Jan 30, 2014 at 14:12
  • 1
    The issue here is that the web fundamentally does not work like that. The correct solution is session variables, but you have to understand that there is no thread here. Three users requesting multiple pages don't necessarily have a thread "each". If user two goes away for an hour, then comes back, you won't keep a thread idle for them. If you have 20,000 concurrent users you won't hold open 20,000 threads. Indeed, nginx, a webserver widely considered by many to be about the fastest available does not thread at all (though it does suffer for that when serving dynamic content)
    – Phoshi
    Commented Jan 30, 2014 at 14:20
  • @Phoshi I agree with you, and I regret the way I phrased my question. However, the question is about these individual requests. Thanks for the correction and insight!
    – Some guy
    Commented Jan 30, 2014 at 14:25
  • 2
    @Rakesh: You're looking for "session" variables, then. In Java access to that is implemented as the session scope, similarly to the request scope.
    – Phoshi
    Commented Jan 30, 2014 at 14:35
  • ThreadLocal, pretty basic construct in Java, explained in tutorials for beginners
    – gnat
    Commented Jan 30, 2014 at 14:41

1 Answer 1

2

A ThreadLocal is what you want. However, in your situation, I think that you should go for Session scoped variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.