Server Side Request Timeout for long running http requests - Java Servlet

48 views Asked by At

With the following sample servlet, which simulates some work being done, there are some requests which will complete in around 10s and others around 60s. The client has requested that we "timeout" any requests that run longer than 30s. It is not desirable to modify the application code with this timeout setting, as this timeout request is specific to one instance of the application and one client.

Is this something that should be done at the Application Server scope, or the HTTP Server scope?

The application is deployed in WebSphere 9, and also in TomEE+ 8. We're using Apache HTTP Server 2.4.x.

What is the best way to accomplish this "timeout"? Would the result be a 408, 504, or something else? Thanks in advance.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    long startTime = System.currentTimeMillis();
    
    try {
        
        Random r = new Random();
        if(r.nextBoolean()) {
            //simulate long running task
            Thread.sleep(60 *1000);
        }else {
            //simulate normal task
            Thread.sleep(10 * 1000);
        }
        
    }catch(InterruptedException e) {
        System.err.println(this.getClass().getSimpleName() + " Interrupted " + e);
    }
    
    long endTime = System.currentTimeMillis();
    
    response.setStatus(200);
    response.setContentType("text/plain");
    response.getWriter().write("Work completed in " + (endTime-startTime) + " milliseconds");
    response.getWriter().flush();
    response.getWriter().close();
}
0

There are 0 answers