I see a lot of people saying that:
“there is only one instance of servlet per application”.
Surely it gives you some information and knowing this will save you from a lot of strange, unexpected errors. However, the above statement is not very accurate and precise. It’s useful to know what is the actual contract between the web container and developer.
Moreover, a lot of questions arise because of the multi-threading issues, so let me sum this up backing my words with Servlet 3.0 Maintenance Release specification:
Assuming we’re working in a non-distributed environment, there is only one servlet instance per definition:
2.2 Number of Instances
For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration.
So, it’s not allowed for the container to pool servlet instances. There is a strict requirement that there is only one instance per definition. This per definition part is also important because if you define two servlets with different names but referring to the same class, you’ll end with different instances of this servlet:
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>com.myservlet.MyServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>servlet2</servlet-namesss>
<servlet-class>com.myservlet.MyServlet</servlet-class>
</servlet>
However, the number of servlet instances can also be affected by implementing deprecated SingleThreadModel
. This
interface is supposed to ensure that only one Thread
can access the Servlet at a given time. Therefore, it might do
so by serializing requests or by pooling multiple servlet instances:
2.2 Number of Instances
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.
Finally, if you mark your web application as a distributed application (<distributable />
sub-element of the
<web-app>
in web.xml
) and you will implement depreciated SingleThreadModel
than you can end with a pool of
servlet instances per definition in each of the JVM of your distributed environment:
2.2 Number of Instances
However, if the servlet in a distributable application implements the SingleThreadModel interface, the container may instantiate multiple instances of that servlet in each JVM of the container.
As you can see the answer “there is only one servlet instance” is not very precise. It gives you an important information regarding multi-threading, but it’s not 100% complete and precise.