This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
1. Is init() method called for ONLY once for a servlet ? In other words, before the servlet instance is created, server calls init() ? 2. Under what circumstance will server create another servlet instance for the same Servlet ? (Forget the case when two URI map to the same servlet class). Is it when the server finds that there is no request for this servlet for a certain amount of time, then it garbage colletc this instance, then if there comes up with a new client request, it creates another new servlet instance ? Is it how it works ?
Two situations I can think of: 1- your servlet implements SingleThreadModel 2- your web app is distributed across several JVMs... you could have one instance per JVM.
Joined: Apr 15, 2003
Originally posted by Jessica Sant: Two situations I can think of: 1- your servlet implements SingleThreadModel 2- your web app is distributed across several JVMs... you could have one instance per JVM.
Jessica, I am not sure if I understand you correctly. Do you mean "init() is called for only once for one servlet instance" only if it is under the two conditions you just mentioned ?
If your servlet implemets SingleTreadedModel interface there will be one instance of your class for each request. Then the init method will be called at each time. Otherwise there can be atmost just one instance of your servlet per JVM. The init method is called just before a servlet is placed into service by the servlet container. Destry is called just before it is taken out of service. As far as I know Servlet container may take a servlet out of service. But before doing so it will call destroy method.Them it will be entitled for garbage collection. And Servlet Container might take the servlet back into action. But before that it will call init method. Therefore there is no gurantee that a init() method is called just once. But followings are definitely guranteed(assuming server doesn't crash). 1.After putting a servlet into action init() is called. 2. Before stopping it destroy() is called.