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?

2

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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...

1 Comment

Im afraid want the timeout to happen inside the thread itself and not the place which creates the thread.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.