Many methods of my Servlet use HTTPSession. It is thread-safety to declare HTTPSession variable as instance variable?
Asked
Active
Viewed 615 times
2 Answers
2
By defaut Servlets are not thread safe. And moreover, a servlets instance will invoked for many clients. It is absolutely wrong to have session as instance variable.
Reference:

Ramesh PVK
- 15,200
- 2
- 46
- 50
-
even if I get session variable by getThreadLocalRequest.getSession() ? – WelcomeTo Feb 15 '12 at 06:25
-
-
getThreadLocalRequest() means getting the thread local object. which is thread safe becuase before on every request intialization the thread local would have been set. I am not sure which framework it is, i just have reffered you some useful links. – Ramesh PVK Feb 15 '12 at 06:55
-
ok thanks.. i.e. if I get session using thredLocal I can set this session as instance variable? – WelcomeTo Feb 15 '12 at 07:08
-
No, just use request.getSession(). You can use thread local when you want to access session in classes other than servlets which do not have request or session variable readily available. – Ramesh PVK Feb 15 '12 at 07:19
1
No, it is not safe. a servlet is created when the application starts. The Servlet has only one instance (which means multiple requests/clients use the same servlet), which is why you should avoid having any instance variables.

epoch
- 16,396
- 4
- 43
- 71
-
But session is unique object for each user. So even if I get session by getThreadLocalRequest.getSession() it is not thread-safe? – WelcomeTo Feb 15 '12 at 06:27