Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
2  
How about using session scope? docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html –  Angelo.Hannes Jan 30 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 Jan 30 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! –  Rakesh Jan 30 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 Jan 30 at 14:35
    
ThreadLocal, pretty basic construct in Java, explained in tutorials for beginners –  gnat Jan 30 at 14:41

1 Answer 1

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.