web容器可能决议一个Servlet是否从servic中移除(例如,当一个容器想要接纳内存资源时或者被关闭时)。在上面的场景中,容器会挪用Servlet接口的destroy方式。在方式中,可以释放servlet使用的任何资源,保留持久化状态。destroy方式关闭在init方式中建立的数据库工具。
当servlet被移除时,它的service方式必须所有执行完成。服务器在所有请求被响应或者在一个特定时间后,通过挪用destroy方式确保这一点的实现。当你的servlet正在执行跨越服务器超时时间的长义务时,这些操作直到destroy方式被挪用前都在执行。你必须确保任何持有客户端请求的线程完成。
本节的其余部分将先容若何执行以下操作:
要跟踪服务请求,需要在servlet类中包罗一个变量,这个变量用来统计运行的service方式数目。这个变量需要使用同步方式增量、减量和返回变量值。
public class ShutdownExample extends HttpServlet { private int serviceCounter = 0; ... // Access methods for serviceCounter protected synchronized void enteringServiceMethod() { serviceCounter++; } protected synchronized void leavingServiceMethod() { serviceCounter--; } protected synchronized int numServices() { return serviceCounter; } }
当每次进入service方式时都需要增进变量值,每次脱离service方式时都需要减小变量值。这是你要在HttpServlet子类覆写父类service方式的缘故原由之一。新方式需要挪用super.service()保留原始的service方式的内容。
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException { enteringServiceMethod(); try { super.service(req, resp); } finally { leavingServiceMethod(); } }
为了确保一个清洁的关闭,在所有请求完成前你的service方式不能释放任何共享资源。做到这一点的一部分是检查service的数目。另外一部分是通知长时间运行的义务是时刻关闭了。为了能通知到位,需要另一个变量。这个变量需要有通常的接见方式。
public class ShutdownExample extends HttpServlet { private boolean shuttingDown; ... //Access methods for shuttingDown protected synchronized void setShuttingDown(boolean flag) { shuttingDown = flag; } protected synchronized boolean isShuttingDown() { return shuttingDown; } }
下面是一个使用这些变量提供清洁的关闭方式的示例:
public void destroy() { /* Check to see whether there are still service methods /* /* running, and if there are, tell them to stop. */ if (numServices()> 0) { setShuttingDown(true); } /* Wait for the service methods to stop. */ while (numServices()> 0) { try { Thread.sleep(interval); } catch (InterruptedException e) { } } }
提供清洁关闭的最后一步是使任何长时间运行的方式都对照规范。可能需要历久运行的方式需要检查通知他们关闭的变量并在需要时强制打断正在执行的事情。
public void doPost(...) { ... for(i = 0; ((i < lotsOfStuffToDo) && !isShuttingDown()); i++) { try { partOfLongRunningOperation(i); } catch (InterruptedException e) { ... } } }
1.阿里云: 本站现在使用的是阿里云主机,平安/可靠/稳固。点击领取2000米代金券、领会最新阿里云产物的种种优惠流动点击进入
2.腾讯云: 提供云服务器、云数据库、云存储、视频与CDN、域名等服务。腾讯云各种产物的最新流动,优惠券领取点击进入
3.广告同盟: 整理了现在主流的广告同盟平台,若是你有流量,可以作为参考选择适合你的平台点击进入
链接: http://www.fly63.com/article/detial/2976