开发者

How to let the servlet container (Tomcat) interrupts/destroys a servlet request?

I am new in Servlet, I used the following code to read some inputStream,

class MyServlet implements Servlet{
  void service(ServletRequest req, ServletResponse res){
  InputStr开发者_C百科eam inA, inB, inC;
   //...
   inA.read(); // May block
   inB.read(); // May block
   inC.read(); // May block
   // ...
   }
 }

How to let the servlet container (Tomcat) interrupts/destroys MyServlet after some configurable time. And in this case which method(s) will it call?

thanks in advance,,,


I don't believe you can do that using Tomcat (or another servlet engine).

The simplest way may be to spawn off the time-consuming process in a separate thread, invoke that and time out on that invocation. You can do that easily by using a FutureTask object and calling get() on it, specifying a timeout. You'll get a TimeoutException if the task takes too long, and you can use the servlet to report this (nicely) to the user.

e.g. (very simple)

FutureTask f = new FutureTask(new Runnable{...});
try {
   Object o = f.get(TIMEOUT, UNITS)
   // report success
}
catch (TimeoutException e) {
   // report failure
}


You don't call those methods, the container does.

I'd wonder why you would do this. Do you really want to re-read those files with every request? If you need the contents, I'd prefer to see you read them in the init method and cache them.


This is perhaps the best approximation without using your own threads: The service method can throw javax.servlet.UnavailableException which will signal container that the servlet is not available temporarily or permanently.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜