0

Suppose I'm inside a thread and I have a call to an external function like

Response resp = ResponseSender.getResponse();

Suppose I don't get a response within t seconds , I want the request to timeout and execute the next line. How do I do this?

Aneesh
  • 1,703
  • 3
  • 24
  • 34
  • Isn't this what you are looking for: http://stackoverflow.com/questions/4978187/apply-timeout-control-around-java-operation – boutta Aug 29 '13 at 07:20
  • 1
    I believe that this is what you are looking for : http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread – Svetlin Zarev Aug 29 '13 at 07:22

3 Answers3

2

Encapsulate the Respnse in a FuturTask, there is a method get(long timeout, TimeUnit unit) to do that.

Salah Eddine Taouririt
  • 24,925
  • 20
  • 60
  • 96
0

This can easily be obtained by putting your coded in a Thread, start it off like this:

private static class TimeoutJob implements Runnable {
private Response resp;
public void run() {
  resp = ResponseSender.getResponse();
}
public Response getResponse() {
  return resp;
}

in your code put this:

TimeoutJob tj = new TimneoutJob();
Thread t = new Thread(tj);
t.start();
t.join(1000); // try to join the thread so waiting for the response to comeback, having a timeout of 1000 milliseconds
if (tj.getResponse() != null) // -> you have a response...

There is an interrupted exception that needs to be catched so this code is not 100% complete but you catch my drift.

Note: that this will give you the timeout capability but the ResponseSender is still running the getResponse() code and you did not interuupted that. You probably are better of in redesinging the ResponseSender class to support timeouts and properly close resources when a timeout occurs...

GerritCap
  • 1,606
  • 10
  • 9
  • Im afraid want the timeout to happen inside the thread itself and not the place which creates the thread. – Aneesh Aug 29 '13 at 07:26
0

If you are using an URL / URLConnection underneath, use setConnectTimeOut and setReadTimeout. Otherwise the other answers will do.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138