servlet thread-Safe servlet multithreaded struts 1 and Struts 2 thread-safe

Source: Internet
Author: User
Tags instance method

First we have to understand the lifecycle of the servlet:

The server creates only a single instance of each servlet, and its Init method is invoked the first time the servlet is created, so Init is where the one-time setup code is placed, and then a thread is created for each user's request, which calls the instance method that was created earlier. Multiple concurrent requests typically cause multiple threads to invoke service (thread safety) at the same time, and the service method invokes the Doxxx method based on the type of the HTTP request received. Finally, if the server unloads a servlet, it calls the servlet's Destroy method.

Whether the servlet is thread safe.

Typically, a new thread is created for each user request after the system generates only a single instance of the servlet. If many requests come at the same time, multiple threads may access the same Servlet object concurrently. So we have to be careful to synchronize access to fields as well as global variables and other shared data, because multiple threads may access the same data at the same time. (Multiple threads do not share local variables).


Workaround:

In principle, you can have the servlet implement the Singlethreadmodel interface to prevent multithreaded access

public class Servlet1 extends HttpServlet implements singlethreadmodel{

........

}

Implement this interface. In most cases, the system queues all requests, sending only one request to a single servlet instance at a time. However, the server can also create a pool of multiple instances, at which time each instance can request processing, at which point we do not need to worry about simultaneous access to the Team Servlet general field (instance variable), but must synchronize access to the class variable or shared data stored outside the servlet.

In most cases, Singlethreadmodel is not a good option. If the servlet is accessed frequently, synchronizing access to the servlet causes significant performance damage (wait time). The server cannot process pending requests for the same servlet while the servlet waits for I/O, database access, and other operations.

The second problem with Singlethreadmodel is that the servlet specification allows the server to use multiple instances to process requests in lieu of queues for requests for a single instance. As long as each instance processes a request at the same time, the instance sharing method meets the requirements of the specification, but this is not a good solution:

When you use a non-static instance variable to store shared data, Singlethreadmodel blocks concurrent access, but each servlet instance has a separate copy of the instance variable, and the data cannot be shared.

Using static instance variables to store shared data: Singlethreadmodel's shared pool has no advantages, and multiple requests still have concurrent access to static data.

For high volume servlet, it is better to use explicit code synchronization.

In a simple example, 3 schemes are given.

String id = "User ID =" + userId;

Do something ....

UserId = userId + 1;

1: Reduce competition

Sting id = "User ID =" + userid++; This scheme reduces the likelihood of generating incorrect answers, but does not completely eliminate it, and in many cases it is a disaster to reduce the likelihood of errors, and the problem is more difficult to find in testing

2:singlethreadmodel

Modify the servlet as follows

public class UserId extends HttpServlet implements singlethreadmodel{

If the server implements Singlethreadmodel by queuing all requests, it can work, but if the village is heavily accessed concurrently, this approach can result in significant performance losses.

If the server implements Singlethreadmodel by generating multiple instances of the servlet. This approach will fail completely because each instance has its own UserID field.

3: Using Sync

Synchronized (This) {

String id = "User ID =" + userId;

Do something ....

UserId = userId + 1;

}

The thread safety of struts 1 and Struts 2 in the recent use of struts2, you'll see a scope ("prototype") added to the action written by someone else.
This is very strange. Why do you want to add this.
This is not added to the struts1. And the action in Struts1 is a single example. Although I heard that Singleton is an inverse mode, I heard that there are performance problems. But in the use of struts1 did not go into the deep, because we are so used, very natural.

I've seen a lot of questions that didn't add scope when I was querying the data.
Http://blog.csdn.net/foamflower/archive/2009/07/08/4329989.aspx
http://elf8848.javaeye.com/blog/356746
All of this is because no scope is added, causing the last variable value to affect the next request.
There are also the following questions: It also makes me think impassability.
The reference to the Strut2 Authority Guide is as follows:
Threading-Mode comparisons: The Struts1 action is a singleton pattern and must be thread-safe because only one instance of the action handles all requests. A single example strategy limits what Struts1 action can do, and is particularly careful when developing. The action resource must be thread safe or synchronized; The Struts 2 Action object generates an instance for each request, so there is no thread-safety problem.

Because of the design pattern is not very understanding, did so the year struts, has not known struts1 is a single case mode, I do not know where this is reflected from.
And how to pay attention to "thread safety or synchronization" during the development process. Struts2 from where "no thread-safety issues."

So where does the problem of threading actually manifest itself?

After looking up some information. Yes, I do.
Http://hi.baidu.com/platon/blog/item/64a20ff3f96e7fce0b46e031.html
This article is about the most basic servlet multithreading problem.
In fact, the servlet itself is a single instance class in a multithreaded environment. This is how the Web container handles the servlet.

This article knows why Struts1 doesn't take into account threading issues because all of the code is written in the Execute method, all variables are defined inside, so there is no thread safety problem.

And now the STRUTS2 is not the same. Struts2 's action, like a Pojo, defines a lot of class variables. This is a thread safety issue. At this point, you use Scope=prototype to specify a prototype pattern, rather than a single example, which resolves thread-safety issues. Each thread is a new instance ...

Http://hi.baidu.com/niujunkai/blog/item/021964adc130660a4a36d6ab.html
The article also illustrates the crux of the problem.
Reference However, thread synchronization is a method that is not possible, is more complex, and can result in a loss of performance. In the equivalent code, there is no need for synchronization to be much better at writing ease and performance.
What I'm emphasizing here is that the code is always thread-safe and does not need to be synchronized. As follows:
1 constants are always thread-safe because only read operations exist.
2 access to the constructor (new operation) is thread-safe because each time a new instance is created, the shared resource is not accessed.
3 The most important thing is that the local variable is thread safe. Because each method is executed, local variables are created in a separate space, which is not a shared resource. A local variable includes a parameter variable for the method.
The Struts User Guide has:
Only with local variables-the most important principle that aids in Thread-safe coding be to-use only local Variables, no T instance variables, in your Action class.
Use local variables only. The most important principle of writing thread-safe code is to use only local variables in the action class and not use instance variables.

There is also this article
http://www.javaeye.com/topic/225749

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.