public Servlet allocate() throws ServletException {
// If not SingleThreadedModel, return the same instance every time
if (!singleThreadModel) {
// Load and initialize our instance if necessary
if (instance == null) { // 如果instance为null 就调用loadServlet
synchronized (this) { // 返回一个新的
if (instance == null)
instance = loadServlet();
}
}
if (!singleThreadModel) { //如果已经有instance了 直接返回就ok
countAllocated++;
return (instance);
}
}
synchronized (instancePool) { //能运行到这里,说明一定是实现了singleThreadModel
while (countAllocated >= nInstances) { //会给池中不断地放置servlet
if (nInstances < maxInstances) {
instancePool.push(loadServlet());
nInstances++;
} else {
instancePool.wait();
}
}
countAllocated++;
return (Servlet) instancePool.pop(); //最后返回顶上的一个
}所以我们能得出一个结论,如果servlet没有实现singleThreadModel,那么第一次请求它时,返回一个新的,第二次就还是它本身了。如果实现了singleThreadModel,tomcat会维持一个servlet池,每次请求,都给你一个池里的对象。因此最好的方法就是引入ThreadLocal模式。这个模式,我们在后面会再讲。
http://blog.csdn.net/dlf123321/article/details/41247693
http://www.cnblogs.com/gw811/archive/2012/09/07/2674859.html
原文地址:http://blog.csdn.net/dlf123321/article/details/42222303