why apache servlet is singleton? [duplicate]

纵然是瞬间 提交于 2020-01-07 09:56:08

问题


  HttpServletRequest request;
  HttpServletResponse response;

  public void doGet(HttpServletRequest request , HttpServlet response){
         this.request = request;
         this.response = response;
  }

What happens if this servlet receives multiple requests at a time?

We faced a response mismatch issue. Is this an issue?


回答1:


Its an issue and it is never advisable to declare HttpServletRequest request/HttpServletResponse response as an instance variable. Actually Servlet is implementing single thread model that means only one servlet instance is created. And one thread for each request. So if their are many requests then thr must be many threads and each sharing same servlet instance inturn it will create data mismatch or data inconsistency problem. Threads will work on the same instances.




回答2:


Your web application container only loads one instance of a servlet.

To write thread-safe servlets, you should almost never use instance variables at all. Setting the request and response as instance variables is just plain wrong. The instance of the servlet doesn't belong to a single request.

If you need to make the elements of the request or response available to other methods, pass them to those methods. You don't need them as instance variables.




回答3:


Of course it's an issue. A servlet is a singleton. The same servlet instance is used to handle all the requests to this servlet. And requests are of course handled concurrently. This means that thread1 will use the request and response normally handled by thread2 if you do that.




回答4:


Quoting the Servlet Specification

"Each request and response object is valid only within the scope of a servlet’s service method, or within the scope of a filter’s doFilter method. Containers commonly recycle request objects in order to avoid the performance overhead of request object creation. The developer must be aware that maintaining references to request objects outside the scope described above is not recommended as it may have indeterminate results. "




回答5:


This will definitely create issue, any instance variable is shared as servlet is singleton so concurrent request and response object will be overrided .




回答6:


What happens is that your servlet instantly becomes non-reentrant and will certainly fail the first time it is invoked by more that one client simultaneously. You must not do this.



来源:https://stackoverflow.com/questions/10665223/why-apache-servlet-is-singleton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!