Sevlet is single-threaded or multi-threaded, how to write a secure servlet program under multiple threads

Source: Internet
Author: User
Tags static class terminates

Sevlet is single-threaded or multi-threaded, how to Write a secure servlet program

The first is clear: the servlet is a single instance, that is, there is only one instance for the same business request. Different business requests can be distributed to produce multiple instances.
Second: The reason of single instance I think because a single instance can handle a request, just like Ibatis's Querydao, Updatedao are single-instance.
Again: Why a single instance can handle a request because the servlet is a single-instance multithreading.
http://hiyachen.cublog.cn[email protected]
Look at the code first:
Package hiya.test;

public class Servlet {
private static servlet instance=new servlet ();
Private Servlet () {

}
public static Servlet getinstance () {
return instance;
}
public void Services () {
System.out.println ("Do something");
}

Static class Client extends thread{
Private servlet servlet;
Public Client (servlet servlet) {
This.servlet=servlet;
}
public void Run () {
Servlet.services ();
System.out.println ("Do something");
}
}

public static void Main () {
Servlet servlet=servlet.getinstance ();
for (int i=0;i<10;i++) {
Client Client=new Client (servlet);
Client.start ();
}
}
}

This is the implementation code for single-instance multithreading. (I really want to paste out the JDK source code.) )

Servlet single-Instance multithreading principle:
The Init method in the servlet is called only when it is started (for example, when the Web container starts, to see the settings of the loadonstartup), i.e. it is initialized only once, which is a single instance.
The servlet calls the service method when processing the request, which can handle requests from multiple clients.
When specifically visited:
The JSP "translates into Servlet" in the Web container is executed by the container, which itself is the multi-threading provided, A,b,c 3 accesses, establishes 3 separate thread groups, and runs a servlet. Execute in turn.
This solves the confusion of multiple users in the same instance.
Some points to note:
1:servlet first is not a ready-made thread.   The 2:servlet architecture is built on the Java multithreading mechanism, whose life cycle is the responsibility of the Web container. The servlet container automatically uses techniques such as the thread pool to support system operation
3: Set jsp:<%@ page isthreadsafe= "false"%> to implement single thread. When you need to ensure data consistency, you have to consider a single thread when you have to handle threading security issues yourself.



ways to ensure thread safety
Compared with ASP and PHP, servlet/jsp technology has high execution efficiency because of its multi-threaded operation. Because servlet/jsp is executed in multithreaded mode by default, you need to take a very careful look at the security of multithreading when writing code.   However, many people do not pay attention to multithreading security issues when writing servlet/jsp programs, which often results in the program written by a small number of user access without any problems, and when the concurrent users rise to a certain value, there will be a lot of trouble. The multithreaded mechanism servlet architecture of a servlet is built on the Java multithreading mechanism, and its life cycle is the responsibility of the Web container. When a client requests a servlet for the first time, the servlet container instantiates the Servlet class based on the Web. XML configuration file. When a new client requests the servlet, the servlet class is typically no longer instantiated, that is, multiple threads are using the instance. The servlet container automatically uses techniques such as the thread pool to support the operation of the system, as shown in 1. Figure 1 servlet thread pool This way, when two or more threads access the same servlet at the same time, multiple threads can access the same resource at the same time, and the data may become inconsistent.   So if you are not aware of thread-safety issues when you build Web Apps with Servlets, you can make the servlet program you write difficult to find. The thread safety of the servlet thread-safety problem is mainly caused by improper use of instance variables, as illustrated by a practical example. Import Javax.servlet. *; Import javax.servlet.http. *; Import java.io. *; public class Concurrent Test extends HttpServlet {printwriter output; public void Service (HttpServletRequest request,   Www.2cto.comHttpServletResponse response) throws Servletexception, IOException {String username; Response.setcontenttype ("text/html; charset=gb2312 "); Username = Request.getparameter ("Username"); Output = Response.getwriter (); Try {Thread. Sleep (5000);//To highlight concurrency problems, set a delay} Catch (interrupted Exception e) {}output.println ("User name:" +username+ "< Br> "); The servlet defines an instance variable output, which is assigned to the user's output in the service method. When a user accesses the servlet, the program runs normally, but when multiple users are concurrently accessing it, it is possible that other users ' information will appear on other users ' browsers. This is a serious problem. In order to highlight the concurrency problem, it is easy to test and observe, we perform a delay operation when we echo the user information. Assuming that the servlet has already been registered in the Web. XML configuration file, existing two users A and B access the servlet simultaneously (you can start two IE browsers, or concurrently on both machines), which is also entered in the browser: a:http://localhost:8080 /servlet/concurrenttest? Username=a b:http://localhost:8080/servlet/concurrenttest? username=b If User B is a bit slower than user A, you will get the output shown in 2: Figure 2 A user and B user's browser output as can be seen from Figure 2, the Web server initiates two threads processing requests from User A and User B, respectively. However, a blank screen is available on user A's browser, and user A's information is displayed on user B's browser. The servlet has a thread insecurity problem.   Here we start by analyzing the memory model of the instance and observing the value of the instance variable output at different times to analyze the reason why the servlet thread is unsafe. The memory model of Java JMM (Java memory models) JMM is primarily intended to prescribe some relationship between threads and memory. According to JMM's design, there is a main memory in the system, and all the instance variables in Java are stored in memory and shared for all threads. Each thread has its own working memory (working memory), the work is composed of two parts of the cache and the stack, the cache is a copy of the variables stored in main memory, the cache may not be the sum of main memory synchronization, that is, the changes in the cache variables may not be immediately written into main memory A thread's local variables are saved in the stack, and the variables in the stack cannot be accessed directly between the threads. According to JMM,We can abstract the memory model of the servlet instance discussed in this paper into the model shown in Figure 3. Figure 3 The JMM model of a servlet instance below, based on the memory model shown in Figure 3, analyzes the changes in the variables involved in the servlet instance and the execution of the thread, as shown in the User A and B threads (referred to as a-thread, B-thread) concurrently, as described in 4. Dispatch moment a thread B thread T1 Access servlet page T2   Access servlet page T3 output=a output username=a Hibernate 5000 ms, let go of CPU T4   output= The output of B (write back to main memory) Username=b sleeps for 5000 milliseconds, yielding CPUT5 on User B's browser to output the value of a thread username, a thread terminates.                   T6   Outputs the value of the B thread's username on User B's browser, and the B thread terminates. Figure 4 The thread scheduling scenario for a servlet instance is clearly seen in Figure 4, because the B thread's modification of the instance variable output overrides the A thread's modification of the instance variable output, causing user A's information to be displayed on User B's browser. If the a thread executes the output statement, the B thread's modification to output has not been flushed to main memory, so the output shown in Figure 2 will not appear, so this is only an accidental phenomenon, but it increases the potential danger of the program. Designing a thread-safe servlet through the above analysis, we know that the incorrect use of instance variables is the main cause of the servlet thread insecurity.   Here are three solutions for this problem and some reference suggestions for the selection of the scheme. 1. Implement the Singlethreadmodel interface This interface specifies how the system handles calls to the same servlet. If a servlet is specified by this interface, then the service method in this servlet will not have two threads being executed concurrently, and there is no thread-safe issue, of course.  This method simply changes the class header definition of the previous Concurrent test class to: public class Concurrent Test extends HttpServlet implements Singlethreadmodel {...} 2. Synchronization of the operation of the shared data using the Synchronized keyword ensures that only one thread can access the protected section at a time, and the servlet in this paper can ensure thread security by synchronizing block operations. The code after the synchronization is as follows: ... PUblic class Concurrent Test extends HttpServlet {...... Username = Request.getparameter ("Username"); Synchronized (this) {Output = Response.getwriter (); Try {Thread. Sleep (5000);} Catch (interrupted Exception e) {}output.println ("Username:" +username+ "<BR>");   }}} 3, avoid using instance variables the thread safety problem in this instance is caused by instance variables, which are thread-safe as long as the instance variables are not used in any of the methods inside the servlet. Fix the above servlet code, change the instance variable to local variable to implement the same function, the code is as follows: ... public class Concurrent Test extends HttpServlet {public void service (HttpServletRequest request, HttpServletResponse Res Ponse) throws Servletexception, IOException {Print Writer output; String username; Response.setcontenttype ("text/html; charset=gb2312 "); The above three methods are tested to show that they all can design a servlet program for thread safety. 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 lot of overhead. Singlethreadmodel is no longer advocated in Servlet2.4, and the performance of the system can be greatly reduced if synchronization is used in the program to protect the shared data to be used. This is because the code block that is being synchronized can only have one thread executing it at the same time, making it handle the throughput of customer requests at the same time, and many customers are in a blocking state. In addition, in order to ensure the consistency of the contents of main memory and the data of the thread, the cache can be refreshed frequently, which will greatly affect the performance of the system. Therefore, in the actual development should also avoid or minimize the synchronization code in the Servlet; SerlAvoiding the use of instance variables in ET is the best choice for ensuring servlet thread safety. From the Java memory model It is also known that the temporary variables in the method are allocated space on the stack, and each thread has its own private stack space, so they do not affect the thread's security. Compared with ASP and PHP, servlet/jsp technology has high execution efficiency because of its multi-threaded operation. Because servlet/jsp is executed in multithreaded mode by default, you need to take a very careful look at the security of multithreading when writing code.   However, many people do not pay attention to multithreading security issues when writing servlet/jsp programs, which often results in the program written by a small number of user access without any problems, and when the concurrent users rise to a certain value, there will be a lot of trouble. The multithreaded mechanism servlet architecture of a servlet is built on the Java multithreading mechanism, and its life cycle is the responsibility of the Web container. When a client requests a servlet for the first time, the servlet container instantiates the Servlet class based on the Web. XML configuration file. When a new client requests the servlet, the servlet class is typically no longer instantiated, that is, multiple threads are using the instance. The servlet container automatically uses techniques such as the thread pool to support the operation of the system, as shown in 1. Figure 1 servlet thread pool This way, when two or more threads access the same servlet at the same time, multiple threads can access the same resource at the same time, and the data may become inconsistent.   So if you are not aware of thread-safety issues when you build Web Apps with Servlets, you can make the servlet program you write difficult to find. The thread safety of the servlet thread-safety problem is mainly caused by improper use of instance variables, as illustrated by a practical example. Import Javax.servlet. *; Import javax.servlet.http. *; Import java.io. *; public class Concurrent Test extends HttpServlet {printwriter output; public void Service (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException { String username; Response.setcontenttype ("Text/html; charset=gb2312 "); Username = Request.getparameter ("Username"); Output = Response.getwriter (); Try {Thread. Sleep (5000);//To highlight concurrency problems, set a delay} Catch (interrupted Exception e) {}output.println ("User name:" +username+ "< Br> "); The servlet defines an instance variable output, which is assigned to the user's output in the service method. When a user accesses the servlet, the program runs normally, but when multiple users are concurrently accessing it, it is possible that other users ' information will appear on other users ' browsers. This is a serious problem. In order to highlight the concurrency problem, it is easy to test and observe, we perform a delay operation when we echo the user information. Assuming that the servlet has already been registered in the Web. XML configuration file, existing two users A and B access the servlet simultaneously (you can start two IE browsers, or concurrently on both machines), which is also entered in the browser: a:http://localhost:8080 /servlet/concurrenttest? Username=a b:http://localhost:8080/servlet/concurrenttest? username=b If User B is a bit slower than user A, you will get the output shown in 2: Figure 2 A user and B user's browser output as can be seen from Figure 2, the Web server initiates two threads processing requests from User A and User B, respectively. However, a blank screen is available on user A's browser, and user A's information is displayed on user B's browser. The servlet has a thread insecurity problem.   Here we start by analyzing the memory model of the instance and observing the value of the instance variable output at different times to analyze the reason why the servlet thread is unsafe. The memory model of Java JMM (Java memory models) JMM is primarily intended to prescribe some relationship between threads and memory. According to JMM's design, there is a main memory in the system, and all the instance variables in Java are stored in memory and shared for all threads. Each thread has its own working memory (working memory), which consists of a cache and a stack, and the cache holds a copy of the variables in main memory.The cache may not be the sum of main memory synchronization, that is, the changes in the cache variables may not be immediately written into main memory; the stack holds the thread's local variables, and the threads cannot directly access the variables in the stack. According to JMM, we can abstract the memory model of the servlet instance discussed in this paper into the model shown in Figure 3. Figure 3 The JMM model of a servlet instance below, based on the memory model shown in Figure 3, analyzes the changes in the variables involved in the servlet instance and the execution of the thread, as shown in the User A and B threads (referred to as a-thread, B-thread) concurrently, as described in 4. Dispatch moment a thread B thread T1 Access servlet page T2   Access servlet page T3 output=a output username=a Hibernate 5000 ms, let go of CPU T4   output= The output of B (write back to main memory) Username=b sleeps for 5000 milliseconds, yielding CPUT5 on User B's browser to output the value of a thread username, a thread terminates.                   T6   Outputs the value of the B thread's username on User B's browser, and the B thread terminates. Figure 4 The thread scheduling scenario for a servlet instance is clearly seen in Figure 4, because the B thread's modification of the instance variable output overrides the A thread's modification of the instance variable output, causing user A's information to be displayed on User B's browser. If the a thread executes the output statement, the B thread's modification to output has not been flushed to main memory, so the output shown in Figure 2 will not appear, so this is only an accidental phenomenon, but it increases the potential danger of the program. Designing a thread-safe servlet through the above analysis, we know that the incorrect use of instance variables is the main cause of the servlet thread insecurity.   Here are three solutions for this problem and some reference suggestions for the selection of the scheme. 1. Implement the Singlethreadmodel interface This interface specifies how the system handles calls to the same servlet. If a servlet is specified by this interface, then the service method in this servlet will not have two threads being executed concurrently, and there is no thread-safe issue, of course.  This method simply changes the class header definition of the previous Concurrent test class to: public class Concurrent Test extends HttpServlet implements Singlethreadmodel {...} 2. Synchronize the operation of the shared data using SynchroniThe Zed keyword guarantees that only one thread can access the protected section at a time, and the servlet in this paper can ensure thread security by synchronizing block operations. The code after the synchronization is as follows: ... public class Concurrent Test extends HttpServlet {...... Username = Request.getparameter ("Username"); Synchronized (this) {Output = Response.getwriter (); Try {Thread. Sleep (5000);} Catch (interrupted Exception e) {}output.println ("Username:" +username+ "<BR>");   }}} 3, avoid using instance variables the thread safety problem in this instance is caused by instance variables, which are thread-safe as long as the instance variables are not used in any of the methods inside the servlet. Fix the above servlet code, change the instance variable to local variable to implement the same function, the code is as follows: ... public class Concurrent Test extends HttpServlet {public void service (HttpServletRequest request, HttpServletResponse Res Ponse) throws Servletexception, IOException {


This article is from the "11100713" blog, please be sure to keep this source http://11110713.blog.51cto.com/11100713/1834143

Sevlet is single-threaded or multi-threaded, how to write a secure servlet program under multiple threads

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.