Before reading this article, please read:
How Tomcat works book note 11 standwrapper on the address below:
http://blog.csdn.net/dlf123321/article/details/41247693
In Tomcat, a user's request is handled by a servlet.
So when the first person requests Servleta, it loads in the ClassLoader inside the Tomcat and gets an instance of the Servleta class.
What happens when the second person asks for Servleta? Is it a new instance or what?
Don't talk more about the code
Public Servlet allocate () throws Servletexception {//If not Singlethreadedmodel, return the same instance every T IME if (!singlethreadmodel) {//Load and initialize our instance if necessary if (instance = = null) {//If instance is null, call Loadservlet synchronized (this) {//return a new if (instance = = null) instance = Loadservlet (); }} if (!singlethreadmodel) {//If there is already instance the direct return is OK countallocated++; return (instance); }} synchronized (Instancepool) {//can run here, the description must be implemented Singlethreadmodel while (countallocated >= ninstances) {//will continuously place servlet if (Ninstances < maxinstances) {instance in the pool Pool.push (Loadservlet ()); ninstances++; } else {InstancepooL.wait (); }} countallocated++; Return (Servlet) Instancepool.pop (); Finally return to the top one}So we can conclude that if the servlet does not implement Singlethreadmodel, then the first time it is requested, it returns a new one, and the second time it is itself. If the implementation of SINGLETHREADMODEL,TOMCAT will maintain a servlet pool, each request gives you a pool of objects.
If you have read the blog I recommended at the beginning of my article, I should understand why Singlethreadmodel will be discarded.
So in the final analysis, if there is no singelthreadmodel, multithreading problem how to do?
Now that I ask, I have to ask a question: What if it's multi-threaded?
Please refer to
Http://www.cnblogs.com/gw811/archive/2012/09/07/2674859.html
Also in the above article, if we use only local variables instead of instance variables, we can do without synchronized (this) {} for this protection.
Through the above reading we know
The best way to solve threading problems is to avoid using the internal variables of the servlet class. But this is a non-syntactic protection, and programmers can still make this mistake.
So the best way is to introduce threadlocal mode. This pattern, we'll talk about it later.
Resources
http://blog.csdn.net/dlf123321/article/details/41247693
Http://www.cnblogs.com/gw811/archive/2012/09/07/2674859.html
Threading issues in Tomcat