tags:

views:

193

answers:

3

Dear All,,,

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

class MyServlet implements Servlet{
  void service(ServletRequest req, ServletResponse res){
  InputStream 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,,,

+1  A: 

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.

duffymo
thanks,,,how container interrupt service servlet method ?I just need to interrupt service method if it takes a specific timeanymore suggestion?
worldpython
Maybe you can do this with java.nio or wrapping it in a Timer. But the servlet API should not be part of the solution. It's an IO issue.
duffymo
is timer Save to use in servlets?
worldpython
If you create it locally inside the service method it'll only be visible to the thread associated with that HTTP request. Should be okay. Only shared state is problematic.
duffymo
Is there is reference indicate that it is safe to use timer in servlet ?,,,thanks for your effort
worldpython
No reference, just your knowledge regarding thread safety and the docs for something like FutureTask or Timer: http://doc.javanb.com/javasdk-docs-6-0-en/api/java/util/concurrent/FutureTask.html
duffymo
+1  A: 

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
}
Brian Agnew
is it save to use threads in servlet ?
worldpython
Yes. That's not a problem and a common solution to these sort of problems
Brian Agnew
A: 

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.

Chandra Patni