Call destroy() inside init() (Servlets forum at Coderanch) (original) (raw)

Originally posted by amna amna:
So will the servlet be destroyed and not initialized?
I was asked this question in an interview.

I've been wondering why that question gets asked so much.
I guess it would make a good interview question.
If that's the answer you gave, I'm assuming the interview didn't go very well.

There is a link to the servlet spec in my signature.
You might want to download it and read the section that covers the servlet life cycle. It's not a difficult read.

All of the life cycle methods init, destroy, doXxx, etc.. are callback methods. Instead of the spec providing these methods for you to call, you're supposed to implement the functionality of these methods for the container to call.

For instance, if you want something done when the servlet is initialized, you would override one of the init methods and add the code that you want executed in there. Likewise, if you want something to happen when the servlet is removed from service, you would add your code to the destroy method. If you don't override destroy, then nothing happens when destroy is called. You would never call destroy yourself. It is called by the container when the servlet is taken out of service.

So, to answer your question:
If you don't override destroy(), but added a call to it from the init method the container (when the servlet is put into service), will call your init method.
This will cause the default destroy method (which does nothing) to be called. Nothing will happen.
Then, when the servlet is taken out of service, the container will call the default destroy method. Again, nothing will happen.

If you override destroy then, when the servlet is put into service, the container will call the init method which (because you're calling destroy from init) will call the destroy method. When this happens, whatever code you put into destroy will be executed. Then, when the servlet is taken out of service, the container will call destroy and your code will be executed again.

Does this help?
[ May 09, 2008: Message edited by: Ben Souther ]