You should NOT be calling the destroy method in the servlet interface. Read the JavaDocs - destroy is called by the servlet container when a servlet instance is being taken out of service. Where do you people get these bizarre ideas? You should review the JavaDocs to understand which methods exist to be called by the servlet container.
The obvious parallel is with finalize, which should ALSO not be called by your program code, which is called by the GC process.
If your design needs object cleanup code that you want to call, make your own method. Bill
Hi Wiliam, I know that Servlet's destroy() is called by the servlet container to indicate that the servlet is being taken out of service.This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state in memory.
But then with this method we have got Object's finalize() method in the Servlet class.and it does the same job of releasing non mem resources. So now can u pls tell in this when exactly destroy & finalize will be called & in which sequence. And can i have both the methods implemented in my class then what code i shld write it in that.
Waiting for reply. Thanks Aparna.
Author and all-around good cowpoke
Joined: Mar 22, 2000
You can tell I am out of touch with the kind of interview questions you may get asked - I guess you truly have to be ready for anything, even really bizarre ideas.
Can destroy and finalize be addressed from developer code? Sure, why not - there is nothing magic about the servlet environment that would keep you from doing it.
Since destroy is the method that the servlet API requires, you should use it. The finalize method should be regarded as the absolute last chance to clean up as an object is removed from memory, and not the normal routine cleanup method. It is especially important for classes that may tie up operating system resources. Look at the way finalize is used in the java.io.FileInputStream class for example.
Naturally, since destroy is called while the servlet container still has a reference to the servlet object, it will be called before the GC process ever gets around to calling finalize. You can rely on destroy being called at a given point in the servlet class life-cycle but you can't rely on when finalize will be called, so I would put all cleanup code in destroy.
subject: difference between destroy() & finalize()