Is servlet the singleton?

后端 未结 3 1406
长发绾君心
长发绾君心 2020-12-30 20:36

Reading some book that said the servlet is singleton from the container side. Is this true?

However even it is a singleton, we need to handle data synchronization et

相关标签:
3条回答
  • 2020-12-30 21:16

    No, Servlet is not a Singleton. It may create 2nd Object , depends on the incoming request and the Container behavior.

    0 讨论(0)
  • 2020-12-30 21:29

    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)

    0 讨论(0)
  • 2020-12-30 21:33

    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.

    0 讨论(0)
提交回复
热议问题