描述:
在很多书上都提到HttpServlet都是Singleton模式,因此在Servlet Container里面只会创建一个HttpServlet实例,事实是这样的吗?
代码解析:
public abstract class HttpServlet extends GenericServlet {
...
public HttpServlet() {
// NOOP
}
...
}
我们分析HttpServlet源代码就会发现,其提供了一个public的构造函数,此外也不能找到static的getInstance方法。明显这个和Singleton设计模式有背,那为什么很多书中会提到HttpServlet是Singleton模式。
Java Servlet Specification:
The servlet declaration which is either via the annotation as described in Chapter 8, “Annotations and pluggability” or part of the deployment descriptor of the Web application containing the servlet, as described in Chapter 14, “Deployment Descriptor”, controls how the servlet container provides instances of the servlet. For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.
结论:
HttpServlet的实现其实并不是Singleton模式,只是很多Servlet Container只创建了一个Servlet实现。