A non-static method in a class sends an HTTP get request that frequently "hangs" (waits forever for a response); in order to cut it after a certain timeout, I use a Timer
as shown in this SO question.
Every time the method is called and the get is initiated, I expect the timer to start from scratch.
But that's not what happens; what happens is the timer starts the first time the method is called, and continues to run for the duration of the execution of the whole program; and when it times out, it aborts whatever get request is currently running.
Here's my code (simplified):
public void processRequest() throws Exception {
final HttpClient client = HttpClientBuilder.create().build();
final String target = this.someString;
final int timeout = 10;
HttpGet get = new HttpGet(target);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try {
get.abort();
// if the request times out it probably means
// the server is down so we exit the program
// and don't run any more requests
System.exit(1);
}
catch (Exception e) {
// warn that something went wrong
}
}
}, timeout * 1000);
//Execute and get the response
final HttpResponse response = client.execute(get);
final int code = response.getStatusLine().getStatusCode();
if (code == 200) {
// do something with the response, etc.
}
}
processRequest is called once for each instance of the class it belongs to; after the first call, the program exits after the duration of timeout
.
Edit: or maybe it's the first timer that continues to run, and I need to kill it when I receive the get response?
Edit2: ok, that solves it: adding timer.cancel()
when the response is received avoids the problem. But I don't understand why! get
is relative to one instance; how is it possible for a timer coming from a previous instance to abort a get that belongs to another instance?