0

Many methods of my Servlet use HTTPSession. It is thread-safety to declare HTTPSession variable as instance variable?

WelcomeTo
  • 19,843
  • 53
  • 170
  • 286
  • Related: http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading/3106909#3106909 – BalusC Feb 15 '12 at 18:38

2 Answers2

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:

Is a Servlet thread-safe

Write thread safe servlets

Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
  • even if I get session variable by getThreadLocalRequest.getSession() ? – WelcomeTo Feb 15 '12 at 06:25
  • @Hello: What is `getThreadLocalRequest()`? Do you use any framework? – home Feb 15 '12 at 06:40
  • 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