Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we call service() method from destroy() method in Servlet?

This is one of the interview questions I faced a few days ago:

Is it possible to call the service() method from destroy()?

Thanks in advance.

like image 548
JDGuide Avatar asked May 25 '13 02:05

JDGuide


1 Answers

destroy() is a lifecycle method called by the Servlet container when unloading a specific instance of the Servlet. Similarly, the container will call service() when there's a client requesting the Servlet.

Can we call service() method from destroy() method in Servlet?

Short answer: Yes, as service() is a method like any other.

Long answer: You can, but it doesn't make sense. service() requires a request and a response parameters that are usually provided by the container when the Servlet is called. If you are calling service() by yourself, how are you gonna provide those parameters? What for? Are you gonna use null on both? What good is service() for two empty parameters?

Can we call destroy() method from service() method in Servlet?

Yes, again, you can call destroy() from within the service() as it is also a method like any other. Although still strange, this could make sense sometimes, as destroy() will do whatever logic you have defined (cleanup, remove attributes, etc.).


IMPORTANT: Just bear in mind that simply calling destroy() won't unload the Servlet instance. You do not manage the lifecycle of Servlets in the program, the Servlet Container does.

like image 94
acdcjunior Avatar answered Sep 19 '22 07:09

acdcjunior