• Post Reply Bookmark Topic Watch Topic
  • New Topic

Basic question: how many servlet instance are created ?

 
Steve Mutanson
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know servlet uses multiple thread mechanism and that's one reason why it is better than CGI. Now, if I have a "MyServlet" deployed on my server and users can access it --
1. How many instances of "Myservlet" will be created on my server ? Always only one or may be more ?
2. If there is always only ONE instance on server, then in the following snippet --
public class MyServlet extends HttpServlet {
static int count = 0;
int myCount = 0;
...
...
}
it seems there is no much difference or needs to distinguish a "class variable" and a "instance variable" because we only have ONE instance anyway ?
Please help me clarify this.
 
Michael Zalewski
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Usually only one instance of the Servlet object is created. But some advanced containers might create more than one instance under certain circumstances.
Even so, there is a difference between static class variables and instance variables. The static variables get created before the object is constructed. The instance variables get created after the object is constructed.
And even if the container only creates one Servlet object, it might destroy the object (at least I think it can do this). If the object gets destroyed, the instance variables also get destroyed. But the class variables should remain.
 
Ani joshi
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Two instances of Servlet will get created if same servlet class is mapped to two Servlets in web.xml using <servlet-class> element.
In such scenario, every instance will have their copy of instance variables but they will share only one copy of static variable.
Ani
 
Rajdeep Biswas
Ranch Hand
Posts: 224
1
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ani,

Can you please give an overview of such mapping, like a portion of the code from web.xml and its usage.
 
Rob Spoor
Sheriff
Posts: 20817
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ani hasn't been active for 9 years, so I doubt you'll get an answer from him/her.
 
Rajdeep Biswas
Ranch Hand
Posts: 224
1
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No problem Rob, anyone is welcome to answer my question.

Thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65522
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try it for yourself. Just create two servlet declarations from the same class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!