简体   繁体   中英

Calling servlet's init and destroy method withing service method

I was reading about servlet's life-cycle and got this doubt. Can we call servlet's init and destroy method inside overridden servlet's service method like calling any other java method? Will this affect container's actual flow ?

You certainly can call init and destroy from the service method. Depending on what those methods do, ie if they actually destroy the servlet, this is probably unwise.

Say, for example, I have a request that comes in and encounters a problem. I think the easiest way to solve this is to call destroy and then init to "restart" the servlet.

My restart takes non-zero time, another request comes in during that time. This request encounters a problem. It also decides to restart the servlet.

You see where this is going...

I would recommend against fiddling with the servlet lifecycle methods and leave that to the container. If you must call those methods then be very wary of thread synchronisation.

As far as affecting the "container's actual flow" - the container has no way of knowing you called the method and that is why requests keep flooding in. The container will be obliviuous to you calling those methods.

Yes, you can call them, but there is no need to do this. This method used by Servlet containers.

You should use this method if you need to for example initialize internal state.

Methods init() and destroy() defaulty are empty and you should override them to take/release resources (for example).

You can call them and it will not affect servlet lifecycle.

you can call those methods no problem.But they are life cycle methods.Whatever the operations performed by the container that is servlet class instantiation and destroy will not happen at that time.

Whenever called by the container only those operations will happen(object instantiation and destroy)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM