Multi-thread Analysis of servlet Singleton

Source: Internet
Author: User

Servlet Lifecycle:

1. The servlet is loaded and instantiated when the web server is started. The Container runs its init method initialization and runs its service method when the request arrives;

2. doxxx (doget, dopost) method corresponding to the service running request;

3. The server destroys the instance and runs its destory method;


Servlet lifecycle is managed by servlet containers;

(Three concepts: servlet container <Web Container <Application Server

The main task of the servlet container is to manage the servlet lifecycle;

Web containers are also called Web servers. The main task is to manage and deploy Web applications;

The application server is very powerful. It can not only manage and deploy Web applications, but also deploy EJB applications to implement container management transactions...

Web servers deal with HTTP-based requests, while EJB containers interact with database, transaction management, and other service interfaces. Therefore, the application server has many functions.

A common web server is tomcat, but Tomcat is also a servlet server;

Common application servers include Weblogic and websphere, but they all charge fees;

Without servlet containers, you can use web containers to directly access static html pages, such as installing Apache. To display JSP/servlet, you need to install a servlet container; however, servlet containers alone are not enough. They need to be parsed to HTML display, so a Web container is still needed. Therefore, we often regard web containers and servlet containers as one, because both of them have the functions of the other side, and they do not exist independently, such as tomcat!

)


How does servlet process simultaneous access of multiple requests?

By default, servlet containers process multiple requests in a single-instance multi-thread manner.:

1. When the Web server is started (or when the client sends a request to the server), the servlet will be loaded and instantiated (only one servlet instance exists );

2. Container initialization servlet. It mainly reads the configuration file (for example, tomcat, you can set the number of threads in the thread pool through <connector> of servlet. XML, initialize the thread pool, and initialize each parameter value through web. XML );

3. When a request arrives, the servlet container uses the scheduling thread to schedule the worker thread in the thread pool under its management to the requester;

4. The thread executes the servlet service method;

5. End the request, put it back into the thread pool, and wait until it is called;

We can see from the above:

1. servlet Single Instance reduces servlet overhead;

Second, the thread pool is used to respond to multiple requests, improving the request response time;

Third, the servlet container does not care whether the received Servlet Request accesses the same servlet or another servlet, and directly assigns it a new thread. If it is multiple requests of the same servlet, then the servlet service method will be concurrently executed in multiple threads;

4. Each request is received by the servletrequest object, and the servletresponse object responds to the request;


The problem occurs:

When multiple requests from the same servlet arrive, if the servlet contains a member variable, multiple threads may access the resource at the same time to operate on it, resulting in data inconsistency, therefore, thread security issues occur.

Solution:

1. Implement the singlethreadmodel Interface

If a servlet is specified by this interface, no two threads will be executed simultaneously in the service method of this servlet. Of course, there is no thread security problem;

2. Synchronize operations on shared data

Using the synchronized keyword ensures that only one thread can access protected segments at a time. servlet can ensure thread security by synchronizing block operations.

Servletrequest objects are thread-safe, but servletcontext and httpsession are not thread-safe;

The Collection class to be synchronized: vector replaces arraylist, and hsahtable replaces hashmap;

3. Avoid using instance variables (member variables)

Thread security issues are caused by instance variables. As long as instance variables are not used in any method in the servlet, the servlet is thread-safe. (We recommend that you do not define member variables in the servlet. Use local variables instead)

The above three methods can be tested to show that all of them can be used to design thread-safe servlet programs. However, if a servlet implements the singlethreadmodel interface, the servlet engine will create a separate servlet instance for each new request, which will cause a large amount of system overhead. Singlethreadmodel is no longer recommended in servlet2.4. If synchronization is used in a program to protect the shared data to be used, the system performance will be greatly reduced. This is because the synchronized code block can only be executed by one thread at a time, reducing the throughput for simultaneously processing customer requests and blocking many customers. In addition, to ensure data consistency between the main memory and the working memory of the thread, the cache should be refreshed frequently, which will greatly affect the system performance. Therefore, in actual development, we should also avoid or minimize the synchronization code in the servlet; In serlet, avoiding using instance variables is the best choice to ensure servlet thread security. We can also know from the Java memory model that the temporary variables in the method allocate space on the stack, and each thread has its own private stack space, so they do not affect thread security.

Servlet thread security issues are only apparent when a large number of concurrent accesses are made, and are difficult to find. Therefore, pay special attention to this issue when writing servlet programs. Thread security problems are mainly caused by instance variables. Therefore, you should avoid using instance variables in servlet. If the application is designed to avoid using instance variables, use synchronization to protect the instance variables to be used. To ensure the optimal performance of the system, the code path with the minimum availability should be synchronized.

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.