Is servlet the singleton?

Servlet can be initialized as a single instance or a pool of instances.

Here is an extract from <<Java Platform, Enterprise Edition The Java EE Tutorial Release 7>>:

A web container will typically create a thread to handle each request. To ensure that a servlet instance handles only one request at a time, a servlet can implement the SingleThreadModel interface. If a servlet implements this interface, no two threads will execute concurrently in the servlet's service method. A web container can implement this guarantee by synchronizing access to a single instance of the servlet or by maintaining a pool of web component instances and dispatching each new request to a free instance.


Looking at the definition of the Singleton Pattern as defined in the Cunningham & Cunningham, Inc. Wiki

Ensure a class has only one instance, and provide a global point of access to it.

I would say, no. From the perspective of the container one servlet object is accepted and managed including the creation of a ServletContext, but it does not prevent that there is not more than one instance of the servlet.

Regarding such issues I think it's best to look into the corresponding contract, which is in case of servlets defined in the Java Servlet Specification. They have addressed the number of instances of a servlet.

2.2 Number of Instances

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.

In the case where a servlet was deployed as part of an application marked in the deployment descriptor as distributable, a container may have only one instance per servlet declaration per Java Virtual Machine (JVM™). 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.

It only specifies that the container must only use one instance (in the former case) and as EJP has pointed out in the comment:

There is nothing in the Servlet Specification that prevents you from re-instantiating the same servlet class under a different name in the same web-app. Ergo, not a singleton.

Reference Java Servlet Specification 3.0 MR (p.6-7)


No. You can instantiate the same servlet class many times under different servlet names and URLs in the same web container and indeed in the same web-app.

Tags:

Java

Servlets