日期:2014-05-17  浏览次数:20716 次

servlet何时执行destroy方法?
是不是只有在服务器关闭或被手动调用的时候才会执行?
一个servlet长时间不被请求调用,会不会被垃圾收集器清理掉?

------解决方案--------------------
destroy()方法
destroy方法在容器移除servlet 时执行,同样只执行一次。这个方法会在所有的线程的service()方法执行完成或者超时后执行,调用这个方法后,容器不会再调用这个servlet的方法,也就是说容器不再把请求发送给这个servlet。这个方法给servlet释放占用的资源的机会,通常用来执行一些清理任务。
这个接口定义了初始化一个servlet,服务请求和从容器中移除servlet的方法。他们按照下面的顺序执行:
1. servlet被实例化后,用init方法进行初始化
2. 客户端的任何请求都调用service方法
3. servlet被移除服务,调用destroy方法销毁
------解决方案--------------------
destroy方法在容器移除servlet 时执行,同样只执行一次。这个方法会在所有的线程的service()方法执行完成或者超时后执行,调用这个方法后,容器不会再调用这个servlet的方法,也就是说容器不再把请求发送给这个servlet。这个方法给servlet释放占用的资源的机会,通常用来执行一些清理任务。

上面的是jdk API文档中定义,我这儿有个英文版的
Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.

如果有超时时间的话,那这个时间是怎么控制的? 
这个应当不同的应用服务器有不同的实现,没有一个通用的办法吧。
------解决方案--------------------
这个方法只有在servlet的service方法内的所有线程都退出的时候,或在超时的时候才会被调用。