Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables declared outside init() method in servlets

Tags:

java

servlets

I know that for each request to a servlet a the doPost() or doGet() methods are executed and that the code wirtten inside init() method is initialised only once. But what about the code written outside all these methods?
Is that code also threaded? I mean varibles declared in that part, if they are modified in the doPost(), will those changes be reflected for other requsts to the servlets?

like image 217
suraj Avatar asked Jan 18 '23 06:01

suraj


2 Answers

In a normal servlet container, there is only one instance of the servlet object. This object may be used by any number of Threads - one Thread per request. Managing the lifetime of a servlet instance is up to the servlet container.

Hence, when changing the value of a class variable in any method (including init()), it will affect all subsequent requests. Changing or declaring a local variable within your method of course does not influence anything, as the next time the method is called, the local variable is created again (and gets destroyed by the garbage collector when the method is finished).

like image 131
Steven De Groote Avatar answered Jan 29 '23 08:01

Steven De Groote


By defaut Servlets are not thread safe. A single servlet instance will be invoked for many clients. It is absolutely wrong to have state stored inside the servlet as instance variables.

References:

Using session as instance variable

Is a Servlet thread-safe

Write thread safe servlets

like image 44
Ramesh PVK Avatar answered Jan 29 '23 08:01

Ramesh PVK