• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how many instances of my servlet class are created?

 
James Byars
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,

if i have a simple servlet that has a doGet() that simple creates a Date object and then outputs the date to the screen, and say it is accessed by 10 people using their web browsers

1) are 10 servlet instances created? or is just one servlet instance created, and doGet() is executed 10 times, and so each time it is executed, then a Date object is created?
2) how long will the servlet instance stay created for?
3) how long will the date instances stay created for?

thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64959
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Depends.

All else being equal, one. Given that, you should be able to answer the other questions yourself.
 
James Byars
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry, I am still confused.

some places seem to say that after the service() method is called, the servlet dies. Others seem to suggest it is kept alive to handle more requests. Which one is true?

thanks
 
James Byars
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
to elaborate, from http://www.onjava.com/pub/a/onjava/2003/05/14/java_webserver.html:

If the request is for a servlet, load the servlet class and invoke its service method, passing the ServletRequest and ServletResponse objects. Note that in this servlet container, the servlet class is loaded every time the servlet is requested.


what does the servlet class is loaded means? That a new instance is created for the servlet? If so, the above is saying that each time a request happens, a new instance of the servlet is created, surely that is wrong, yes?
 
Soniya Ahuja
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't access the link you've specified. But this is what normally happens

Unless explicitly made to implement the SingleThredModel interface, every servlet has only one instance created. The init method is called once. Every time a new request is made to the servlet, a new thread is created and the service method is called. Thus the service method is called multiple times for the same servlet instance. Thus, in your case, a new date instance would be created every time the service request is called (or rather the doGet is called). If it's called once by 10 users or 10 times by one user, as long as it's a new request, a new instance will be created.

Finally when the servlet is destroyed, the destroy method is called - once for the servlet instance (which is just one in our case).

Good Luck!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic