Variables declared outside the init () method in servlets

I know that for each servlet request the doPost () or doGet () methods are executed and that the code initialized inside init () is initialized only once. But what about code written outside of all these methods?
Is this code also threaded? I mean that the variables declared in this part, if they are changed in doPost() , will these changes be reflected for other servlet requests?

+4
source share
3 answers

In a regular servlet container, there is only one instance of a servlet object. This object can be used by any number of threads - one thread per request. Servlet instance lifetime management depends on the servlet container.

Therefore, if you change the value of a class variable in any method (including init ()), this will affect all subsequent requests. Changing or declaring a local variable inside your method, of course, has no effect, because the next time you call the method, the local variable is created again (and destroyed by the garbage collector when the method is completed).

+5
source

Using defaut, Servlets are not thread safe . One servlet instance will be called for many clients. It is absolutely wrong to have the state stored inside the servlet as instance variables.

Literature:

Using a session as an instance variable

Is servlet thread safe

Create thread-safe servlets

+3
source

Servlet instances are container-aggregated. Thus, any number of Servlet objects can be shared by any number of threads in a real-world scenario. All doXXX () methods and other methods called from them will be separated by Threads.

Therefore, it is highly discouraged to have class level variables (to maintain state) in Servlets. Although you probably have constants, static helper methods, and static variables that are shared by instances and are not constantly changed by clients using Servlet.

Although things are discouraged, it doesnโ€™t stop you from synchronizing variables / methods. This would ensure that only one thread accesses the resource at a time, but there will be a penalty for performance, as threads may need others to release the resource first before taking up the lock.

But there is a better way. If you want to save state with a servlet and want to save variables to one client, your Servlet should implement javax.servlet.SingleThreadModel . If your servlet implements this token interface, the container will know that it maintains state, and therefore only one thread will be serviced per instance.

+1
source

Source: https://habr.com/ru/post/1400963/


All Articles