Search code examples
javatimeout

Apply timeout control around Java operation


I'm using a third party Java library to interact with a REST API. The REST API can sometimes take a long time to respond, eventually resulting in a java.net.ConnectException being thrown.

I'd like to shorten the timeout period but have no means of modifying the third party library.

I'd like to apply some form of timeout control around the calling of a Java method so that I can determine at what point to give up waiting.

This doesn't relate directly to network timeouts. I'd like to be able to try and perform an operation and be able to give up after a specified wait time.

The following is by no means valid Java but does conceptually demonstrate what I'd like to achieve:

try {
    Entity entity = new Entity();
    entity.methodThatMakesUseOfRestApi();
} catch (<it's been ages now, I don't want to wait any longer>) {
    throw TimeoutException();
}

Solution

  • I recommend TimeLimiter from Google Guava library.