單實例多線程
Servlet容器默認是采用單實例多線程的方式處理多個請求的:
1.當web服務器啟動的時候(或客戶端發送請求到服務器時),Servlet就被加載並實例化(只存在一個Servlet實例);
2.容器初始化化Servlet主要就是讀取配置文件(例如tomcat,可以通過servlet.xml的<Connector>設置線程池中線程數目,初始化線程池通過web.xml,初始化每個參數值等等。
3.當請求到達時,Servlet容器通過調度線程(Dispatchaer Thread) 調度它管理下線程池中等待執行的線程(Worker Thread)給請求者;
4.線程執行Servlet的service方法;
5.請求結束,放回線程池,等待被調用;
(注意:避免使用實例變量(成員變量),因為如果存在成員變量,可能發生多線程同時訪問該資源時,都來操作它,照成數據的不一致,因此產生線程安全問題)
單實例有狀態
不是單例,只能說web容器對servlet實例化了一次。servlet只是一個普通的類,它也有自已的構造函數,甚至可以用new的方式new出N多個servlet的實例,但它能正常地處理web請求,就需要交給web服務器(或者叫servlet/jsp容器)來進行管理,比如說tomcat,tomcat通過配置文件獲取映射信息,然后只會在第一次生成servlet的實例,並把它緩存起來,下次再次請求,同樣是取的這個實例,所以它的之前狀態還是被保存起來的,所以共享的數據如果不是線程安全的,會出問題,所以別把數據用成員屬性進行保存,別讓servlet有狀態。
源碼分析
在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,如果聲明多次,也會生成多個實例。