Is servlet the singleton? [duplicate]

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)