Can destroy() be called from inside the service() method of my servlet?

Andrew Postoyanets

destroy() is a servlet life-cycle method called by servlet container to kill the instance of the servlet.

The answer to your question is "Yes". You can call destroy() from within the service(). It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't "unload" the servlet instance itself.

You do not manage the life cycle of servlets in the program; the servlet engine does.

[Alex adds:]

On the other hand, if the question is,

"Is it possible that the servlet container will call destroy() while the servlet is still processing a request inside service() on a different thread?"

then the answer is also yes, but it's a degenerate case. The servlet container is required to wait a reasonable amount of time for current requests to finish processing. So if your request is not totally lagging, it should work out fine. If you're spending more than a few seconds processing a request, that's a UI problem that you should try to work out first.

Check the servlet spec for more details.

BTW, destroy() does not imply garbage collection. The instance may live on in memory long after destroy() is called.