为一个Java Web开发者,你一定了解和学习过Servlet。或许还曾在面试中被问到过Servelt是单例还是多例这个问题。

遇到这个问题,你是否曾深入了解过,还是百度或者Google了一下,得到答案就OK了呢?

我们今天从Servlet规范及Tomcat源码实现的角度,分析下这个问题。

在Servlet规范中,对于Servlet单例与多例定义如下:

“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.

上面规范提到,
如果一个Servlet没有被部署在分布式的环境中,一般web.xml中声明的一个Servlet只对应一个实例。

而如果一个Servlet实现了SingleThreadModel接口,就会被初始化多个实例。实例有多少呢,这里没细说。

下面再从Tomcat的源码中找寻下具体的参考实现是什么样子的。以下代码来源于Tomcat的StandardWrapper类。我把其中不太相关的部分做了删除。

public Servlet allocate() throws ServletException {
boolean newInstance = false;
if (!singleThreadModel) {
// Load and initialize our instance if necessary
if (instance == null) {
synchronized (this) {
if (instance == null) {
try {
instance = loadServlet();
} catch (ServletException e) {}}}}
if (singleThreadModel) {
if (newInstance) {
synchronized (instancePool) {
instancePool.push(instance); //如果实现STM接口,就放到一个栈里
nInstances++;
}}
} else {
if (!newInstance) {
countAllocated.incrementAndGet();
}
return (instance);
}
}
synchronized (instancePool) {
while (countAllocated.get() >= nInstances) {
// Allocate a new instance if possible, or else wait
if (nInstances < maxInstances) {
try {
instancePool.push(loadServlet());
nInstances++;
} catch (ServletException e) {}
} else {
try {
instancePool.wait();
} catch (InterruptedException e) {
// Ignore
}} }
countAllocated.incrementAndGet();
return instancePool.pop();
}}
/**
* Load and initialize an instance of this servlet, if there is not already
* at least one initialized instance. This can be used, for example, to
* load servlets that are marked in the deployment descriptor to be loaded
* at server startup time.
*/
public synchronized Servlet loadServlet() throws ServletException {
// Nothing to do if we already have an instance or an instance pool
if (!singleThreadModel && (instance != null))
return instance; //注意此处,如果存在实例就直接返回
Servlet servlet;
try {
InstanceManager instanceManager = ((StandardContext)getParent()).getInstanceManager();
try {
servlet = (Servlet) instanceManager.newInstance(servletClass);
} catch (ClassCastException e) {
}
if (servlet instanceof SingleThreadModel) {
if (instancePool == null) {
instancePool = new Stack<>();
} //此处,使用Stack存放STM的Servlet
singleThreadModel = true;
}
initServlet(servlet);
} finally {
}
return servlet;
}

那一个实现了SingleThreadModel接口的Servlet,一般会初始化多少个实例呢?
StandardWrapper类中有两个属性,其中maxInstance初始为20。所以上面的问题就有了答案。

/**
* Does this servlet implement the SingleThreadModel interface?
*/
protected volatile boolean singleThreadModel = false;
/**
* Maximum number of STM instances.
*/
protected int maxInstances = 20;

由于SingleThreadModel已经声明为废弃,官方不建议使用。我们这里只是让大家了解下。

总结下,一个Servlet究竟有几个实例呢?受如下几个原因影响:
是否在分布式环境中部署
是否实现SingleThreadModel,如果实现则最多会创建20个实例
在web.xml中声明了几次,即使同一个Servlet,如果声明多次,也会生成多个实例。

作者:侯树成
链接:http://www.jianshu.com/p/caba33d8f3fd
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Servlet到底是单例还是多例你了解吗?的更多相关文章

  1. springboot默认创建的bean是单实还是多例

    转:https://blog.csdn.net/q1512451239/article/details/53122687 springboot默认创建的bean是单实还是多例 曾经面试的时候有面试官问 ...

  2. spring的controller默认是单例还是多例

    转: spring的controller默认是单例还是多例 先看看spring的bean作用域有几种,分别有啥不同. spring bean作用域有以下5个: singleton:单例模式,当spri ...

  3. Spring 的Controller 是单例or多例

    Spring 的Controller 是单例or多例 你什么也不肯放弃,又得到了什么? 背景:今天写代码遇到一个Controller 中的线程安全问题,那么Spring 的Controller 是单例 ...

  4. spring自动注入是单例还是多例?单例如何注入多例?

       单例和多例的区别 :   单例多例需要搞明白这些问题:      1. 什么是单例多例:      2. 如何产生单例多例:      3. 为什么要用单例多例      4. 什么时候用单例, ...

  5. SpringMVC Controller单例和多例

    对于SpringMVC Controller单例和多例,下面举了个例子说明下. 第一次:类是多例,一个普通属性和一个静态属性. 结果:普通属性:0.............静态属性:0 普通属性:0. ...

  6. 详略。。设计模式2——单例变形(多例).。。。studying

    ★ 缓存在单例中的使用("单例+缓存"技术) 缓存在编程中使用非常频繁,有着非常关键的数据,它可以帮助程序实现以空间换取时间, 通常被设计成整个应用程序所共享的一个空间,现要求实现 ...

  7. Spring课程 Spring入门篇 4-7 Spring bean装配之基于java的容器注解说明--@Scope 控制bean的单例和多例

    1 解析 1.1 bean的单例和多例的应用场景 1.2 单例多例的验证方式 1.3 @Scope注解单例多例应用 2 代码演练 2.1 @Scope代码应用 1 解析 1.1 bean的单例和多例的 ...

  8. Spring对象类型——单例和多例

    由于看淘淘商城的项目,涉及到了项目中处理spring中bean对象的两种类型,分别是单例和多例,就在此记录一下,方便加深理解,写出更加健壮的代码. 一.单例和多例的概述 在Spring中,bean可以 ...

  9. @Component默认是单例还是多例?

    @Component默认是单例还是多例?   答: @Component注解默认实例化的对象是单例,如果想声明成多例对象可以使用@Scope("prototype") @Repos ...

随机推荐

  1. java集合类中的迭代器模式

    不说模式的问题,看一个<<设计模式之禅>>里面的例子. 老板要看到公司了各个项目的情况.(我知道我这个概述很让人头大,看代码吧) 示例程序 v1 package Iterato ...

  2. C语言之回文数算法

    "回文"是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如"我为人人,人人为我"等.在数学中也有这样一类数字有这样的特征,成为回文数(pa ...

  3. Myeclipse Db Browser使用

    1.打开Myeclipse,选择菜单栏Window-->Show View-->Other,展开MyEclipse Database,选择DB Browser,打开数据库浏览视图 2. 空 ...

  4. MIDle生命周期详解,以及工作原理

    当MIDlet被应用程序管理器成功地初始化之后,就开始展开了它的生命周期.MIDlet的生命周期完全由应用程序管理器控制,也就是说,当MIDlet要从一个状态变成另外一个状态时,应用程序管理器会调用对 ...

  5. vector向量容器的一些基本操作

    #include <vector> #include <iostream> using namespace std; void print(vector<int>& ...

  6. python标准库Beautiful Soup与MongoDb爬喜马拉雅电台的总结

    Beautiful Soup标准库是一个可以从HTML/XML文件中提取数据的Python库,它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式,Beautiful Soup将会节省数小 ...

  7. [51nod 1515] 明辨是非

    Description 给\(n\)组操作,每组操作形式为\(x\;y\;p\). 当\(p\)为\(1\)时,如果第\(x\)变量和第\(y\)个变量可以相等,则输出\(YES\),并限制他们相等: ...

  8. Spring ioc 详解

    引述:IoC(控制反转:Inverse of Control)是Spring容器的内核,AOP.声明式事务等功能在此基础上开花结果.但是IoC这个重要的概念却比较晦涩隐讳,不容易让人望文生义,这不能不 ...

  9. web集群时session同步的3种方法[转]

    在做了web集群后,你肯定会首先考虑session同步问题,因为通过负载均衡后,同一个IP访问同一个页面会被分配到不同的服务器上,如果session不同步的话,一个登录用户,一会是登录状态,一会又不是 ...

  10. 【转】火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换算法

    关于 GCJ-02 和 BD-09 ,请参考 http://developer.baidu.com/map/question.htm#qa0043 . 算法代码如下,其中 bd_encrypt 将 G ...