Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can servlet container has infinite instances of servlet.

 
mallikarjun dontamsetti
Ranch Hand
Posts: 246
Firefox Browser Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I know servlet is not a singleton class but i read in many tutorials the container creates only one instance for a servlet. Can a container has more than one instance of servlet(may be infinite).
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a servlet is a singleton class. there exists only one instance of a servlet. but there can be multiple instances of a servlet. but it depends upon the particular servlet container you are using. but how ? . your servlet can implement SingleThreadModel interface , which means there wont be more than one thread in your service method. which further means you loose your concurrency. but SingleThreadModel is long deprecated and it should not be used. it was introduced to make your instance variables thread-safe but as you know a well written servlet does not have instance variables. now if your servlet implements STM then it can do either of the two thigns


The purpose of STM is to make your instance variables thread safe. the container can do it in 2 ways.

1. it can create just one instance of servlet and queue the incoming request. only one request enters into service method at a time. this means you lose your concurrency

2. for every request the container creates/allocates new instance/object of servlet. that means no. of servlet objects = no. of requests.

which path the container chooses depends upon the servlet container. it is not dictated in servlet specs.

having said all that the STM model as said earlier is long long deprecated.

Regards
Gurpreet
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(most of the )container create one instance for a servlet for multiple request doesn't not mean servlet is a singleton.
however jee specification deosnt says that container should create a new servlet object per request
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64692
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
gurpeet singh wrote:a servlet is a singleton class. there exists only one instance of a servlet.

That is not correct. Firstly, even if only a single instance of a class is created by a program, that does not automatically make it a singleton. Secondly, the contain can make multiple instances under certain circumstances.

And yes, the SingleThreadModel is long deprecated and should never be used.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic