"Go" multi-user access Servlet,servlet single-instance multithreading

Source: Internet
Author: User

    1. Public class MyClass {
    2. private String variable1;
    3. private static String variable2;
    4. Public MyClass () {
    5. }
    6. public Void Method () {
    7. String Variable3;
    8. }
    9. }

The above is a class that is handy to write, does not have any meaning, just to emphasize some concepts, this is related to this topic:
1) Classification of variables in Java:
A. Instance variables
B. Local variables
C. Static variables
This is not a basic Java tutorial, so it is not exhaustive to each of the basic points of knowledge (the following is a distinction between objects and object variables, <<core java2>> is strictly differentiated, but most textbooks are not too harsh to distinguish them)
A. Instance variables: belong to each object, that is, each object has a copy of this variable. The variable1 on the above point to the instance variable.
B. Local variables: Work in a scope, leaving the scope behind to become garbage. The above variable3 points to local variables, and local variables exist in the method.
C. Static variable: belongs to a class, that is, all objects have a copy. The variable2 above points to a static variable.

2) instantiation of the servlet container:
How the servlet is instantiated, not what we care about, is how many times the servlet is instantiated, whether each request is instantiated or just instantiated once? It's too easy to answer this question:

[Java]View Plaincopy
  1. Public class Test extends HttpServlet {
  2. private static int count = 0;
  3. private int num = 0;
  4. Public Test () {
  5. super ();
  6. Count + +;
  7. System.out.println ("instanced" +count+"Times");
  8. }
  9. public void doget (HttpServletRequest request, httpservletresponse response)
  10. throws Servletexception, IOException {
  11. Response.setcontenttype ("text/html");
  12. num + +;
  13. System.out.println ("was visited" + num+"Times");
  14. }
  15. }



Open the browser, access the specified servlet, and keep refreshing, as a result:
Instantiated 1 of Times
has been visited 1 times
has been visited 2 times
has been visited 3 times

Do not close the browser, and then open a browser access, continuous point refresh, the result is:
has been visited 4 times
has been visited 5 times
has been visited 6 times
has been visited 7 times
has been visited 8 times

Visible to more than just the same user, only one object is instantiated for other users.
In other words, Tomcat only instantiates a servlet, producing an object.

How does the servlet container access the corresponding multi-user concurrently? Answer: Multithreading. Run the Doget or Dopost method with a separate thread for each access. That is, the internal implementation of the servlet container might be:

[Java]View Plaincopy
    1. class .  extends thread{  
    2.     public  void run () {  
    3.         if (request  for  get)   
    4.             servlet.doget ();    // servlet point to the instance of the Servlet class you requested   
    5.        else  if (request  to  post)   
    6.            servlet.dopost ();   
    7. &NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;
    8. }  



This is fine, but some novice programmers may put this error:

[Java]View Plaincopy
  1. Public class Test extends HttpServlet {
  2. private PrintWriter out;
  3. Public Test () {
  4. super ();
  5. }
  6. public void doget (HttpServletRequest request, httpservletresponse response)
  7. throws Servletexception, IOException {
  8. Response.setcontenttype ("text/html");
  9. out = Response.getwriter ();
  10. Out.println (Request.getremoteaddr ());
  11. }
  12. }



What's the result? Single A accesses the test, obtains an instance by Response.getwriter (), and saves it in the out, assuming B executes the response.getwriter () before a, and starts executing out.println ( REQUEST.GETREMOTEADDR ()), when out saves the PrintWriter object that is not obtained by B itself through the getwriter () method, but the result of a run getwriter, then B outputs the address of a. Take a look at the following example:

Create a webapp, called the web, to build the sendname.html HTML file, with the following content:

[Java]View Plaincopy
    1. <body>
    2. <form action="/web/test" >
    3. <input type="text" name="name"/>
    4. <input type="Submit"/>
    5. </form>
    6. </body>



Create a servlet called Test that reads as follows:

[Java]View Plaincopy
  1. Public class Test extends HttpServlet {
  2. private String name;
  3. public void doget (HttpServletRequest request, httpservletresponse response)
  4. throws Servletexception, IOException {
  5. Response.setcontenttype ("text/html");
  6. PrintWriter out = Response.getwriter ();
  7. Name = Request.getparameter ("name");
  8. Out.println ("I input" +name);
  9. try{thread.sleep (5000);} catch (Exception ex) {}
  10. Out.println ("I AM" +name);
  11. Out.flush ();
  12. Out.close ();
  13. }
  14. }



Open 2 sendname.html (http://localhost:8080/web/sendname.html) through the browser and enter names A and B (not more than 5 seconds apart):
The results of the 2 pages shown are:

I input b I am b

I input A I am B

This is the multithreading problem in the servlet. The solution is simple, not to use instance variables, at least not when absolutely necessary.
This problem is more pronounced in JSPs, as the use of <%! The variable declaration made by%> is an instance variable, and if it is to be defined, then use synchronized to add synchronized before the method using the instance variable, which is also deprecated, here is an example:

[Java]View Plaincopy
  1. <%@ page contenttype="text/html;charset=gb2312"%>
  2. <HTML>
  3. <BODY>
  4. <!--number is a critical area--
  5. <%!      int number=0;
  6. synchronized void Countpeople ()
  7. {number++;
  8. }
  9. %>
  10. <% countpeople ();
  11. %>
  12. <P><P> you are the first
  13. <%=number%>
  14. Visitors to our site.
  15. </BODY>
  16. </HTML>


In <%! The way defined in%> is also called by multithreading.
For JSP pages, in addition to using synchronized, you can use the IsThreadSafe of the page directive element to control whether the entire page can be accessed in multiple threads.

"Go" multi-user access Servlet,servlet single-instance multithreading

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.