Wednesday, June 18, 2008

what if destroy() is called from init() in a servlet?

Question: What will happen if the destroy() method is called in the init() method of a Servlet?

Answer: Nothing strange! The destroy() method will simply be called/executed and the control will return back to the next instruction in the init() method.

One of the misconceptions about the destroy() method is that it destroy the servlet object and hence one can think what will happen to the init() method, which is still under execution on an object (the servlet object) which just got destroyed. Huh! as I mentioned that it's a misconception and destroy() method doesn't really destroys the servlet object. Instead it is called just before the Web Container (Servlet Engine to be precise) removes the servlet object from the memory while unloading the servlet. BTW, destroy() method is not supposed to be called by the servlet writer. Though you can call it like any other method, but it's not a good programming practice to do this.

So, if we call the destroy() method from init() then the code written in the destroy() method will be executed and after the completion of the execution of this method, the control will return to the next instruction of the init() method. If you've not overriden destroy() method to put some custom code then it won't be a problem as by default it does nothing, but if you have put some code then you may end up doing something unexpected. For example: Suppose you are reading some value in the init() method from a file stored on the disk and in the destroy() method you're writing the current value in the same (or some other) file. If the call of destroy() method precedes the block of code which reads value from the file then the execution of the destroy() method will end up writing an incorrect value to the file on disk. This is just a sample example, you may think of other more complicated scenarios as well. The bottom line is that the servlet writers are not supposed to call destroy() explicitly and hence they should avoid calling it. Read more about the life cycle of a servlet in this article - Life Cycle of a Servlet >>


No comments: