2

I have some web services exposed using spring web services.

I would like to set a maximun timeout on server side, I mean, when a client invokes my web service It could not last more than a fixed time. Is it possible?

I have found lot of information about client timeouts, but not server timeout.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Felipe
  • 43
  • 4

2 Answers2

0

This is set at the level of the server itself and not the application, so it's application server dependent.

The reason for this is that it's the server code that opens the listening socket used by the HTTP connection, so only the server code can set a timeout by passing it to the socket API call that starts listening to a given port.

As an example, this is how to do it in Tomcat in file server.xml:

<Connector connectionTimeout="20000" ... />
Angular University
  • 42,341
  • 15
  • 74
  • 81
  • Firstly, thanks a lot. I´ve worked on it but it does not work. I´ve read about configuring a valve like org.apache.catalina.valves.StuckThreadDetectionValve to detect the time a thread is alive, but it only logs the fact, not stops it. Why connectionTimeout is not working? Thanks a lot – Felipe Apr 12 '14 at 15:42
0

You can work around this issue by making the web service server trigger the real work on another thread and countdown the time out it self and return failure if timed out.

Here is an example of how you can do it, it should time out after 10 seconds:

public class Test {
private static final int ONE_SECOND = 1_000;

public String webserviceMethod(String request) {

    AtomicInteger counter = new AtomicInteger(0);
    final ResponseHolder responseHolder = new ResponseHolder();

    // Create another thread
    Runnable worker = () -> {
        // Do Actual work...
        responseHolder.finished = true;
        responseHolder.response = "Done"; // Actual response
    };

    new Thread(worker).start();

    while (counter.addAndGet(1) < 10) {
        try {
            Thread.sleep(ONE_SECOND);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (responseHolder.finished) {
            return responseHolder.response;
        }
    }

    return "Operation Timeout"; // Can throw exception here
}

private final class ResponseHolder {

    private boolean finished;
    private String response; // Can be any type of response needed
}

}