Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is init() really called once

 
riohk kurn
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometimes, servlet container may create more than one instance of servlet, in this case, will these instances' init() be called.
As I have checked API, init() is not a static method, so it seems that init() will be called for each instance. However, what're inside init() should be shared with all instances, so, I'm just wondering.
 
Rama Raghavan
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think a review of the servlet lifecycle is in order.
The container does not create multiple instances of the servlet, but spwans multiple threads that calls the service() method, with only a single instantiation of the servlet. So - init() will be called (only) once.
EXCEPT- when the servlet implements SingleThreadModel, in which case init() could be called multiple times, based on a servlet pool managed by the container.
Rama
 
riohk kurn
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are there any containers create more than one instance depending to performance (but not singleThreadServlet)?
 
Rama Raghavan
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NO.
Imagine if you have synchronized a block of code that updates an instance variable, say, count++.
ANY J2EE container must create only one instance of my servlet, otherwise, I cannot rely on a supposedly thread-safe code.
Rama
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic