Servlet到底是單例還是多例你了解嗎?

為一個(gè)Java Web開發(fā)者,你一定了解和學(xué)習(xí)過(guò)Servlet?;蛟S還曾在面試中被問(wèn)到過(guò)Servelt是單例還是多例這個(gè)問(wèn)題。

遇到這個(gè)問(wèn)題,你是否曾深入了解過(guò),還是百度或者Google了一下,得到答案就OK了呢?

我們今天從Servlet規(guī)范及Tomcat源碼實(shí)現(xiàn)的角度,分析下這個(gè)問(wèn)題。

在Servlet規(guī)范中,對(duì)于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.

上面規(guī)范提到,
如果一個(gè)Servlet沒(méi)有被部署在分布式的環(huán)境中,一般web.xml中聲明的一個(gè)Servlet只對(duì)應(yīng)一個(gè)實(shí)例。

而如果一個(gè)Servlet實(shí)現(xiàn)了SingleThreadModel接口,就會(huì)被初始化多個(gè)實(shí)例。實(shí)例有多少呢,這里沒(méi)細(xì)說(shuō)。

下面再?gòu)腡omcat的源碼中找尋下具體的參考實(shí)現(xiàn)是什么樣子的。以下代碼來(lái)源于Tomcat的StandardWrapper類。我把其中不太相關(guān)的部分做了刪除。

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); //如果實(shí)現(xiàn)STM接口,就放到一個(gè)棧里
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; //注意此處,如果存在實(shí)例就直接返回
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;
}

那一個(gè)實(shí)現(xiàn)了SingleThreadModel接口的Servlet,一般會(huì)初始化多少個(gè)實(shí)例呢?
StandardWrapper類中有兩個(gè)屬性,其中maxInstance初始為20。所以上面的問(wèn)題就有了答案。

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

由于SingleThreadModel已經(jīng)聲明為廢棄,官方不建議使用。我們這里只是讓大家了解下。

總結(jié)下,一個(gè)Servlet究竟有幾個(gè)實(shí)例呢?受如下幾個(gè)原因影響:
是否在分布式環(huán)境中部署
是否實(shí)現(xiàn)SingleThreadModel,如果實(shí)現(xiàn)則最多會(huì)創(chuàng)建20個(gè)實(shí)例
在web.xml中聲明了幾次,即使同一個(gè)Servlet,如果聲明多次,也會(huì)生成多個(gè)實(shí)例。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,502評(píng)論 19 139
  • 從三月份找實(shí)習(xí)到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂(lè)視家的研發(fā)崗...
    時(shí)芥藍(lán)閱讀 42,753評(píng)論 11 349
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚_t_閱讀 34,623評(píng)論 18 399
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,253評(píng)論 6 342
  • Servlet如何處理多個(gè)請(qǐng)求訪問(wèn)?Servlet容器默認(rèn)是采用單實(shí)例多線程的方式處理多個(gè)請(qǐng)求的:1.當(dāng)web服務(wù)...
    屎倒淋頭還嚼便閱讀 2,020評(píng)論 1 0

友情鏈接更多精彩內(nèi)容