简体   繁体   中英

Variables declared outside init() method in 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?

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).

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

Servlets instances are pooled by the container. So any number of Servlet Objects can be shared by any number of threads in the real world scenario. All the doXXX() methods and other methods called from them will be shared by Threads.

Hence it is highly discouraged to have class level variables (to maintain state) in Servlets. Although you can surely have Constants, Static helper methods and static variables which are shared by instances also and not constantly modified by clients using the Servlet.

Although things are discouraged, but there is no stopping you from making the variables/methods synchronized. This would ensure that only one thread accesses the resource at a time, but there would be a performance penalty as Threads might have to wait for others to release the resource first before occupying a lock.

But there is a better way, In case you wish to maintain state with a Servlet and want to store variables per client, Your Servlet should implement javax.servlet.SingleThreadModel . If your Servlet implements this marker interface, container would know that it maintains state and hence only one thread would be served per instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM