I am trying to get an Auth ticket from a 3rd party server. I am using FutureTask to perform the task. However, if I don't get response from the server after 10 seconds, I want to timeout the call. At the same time, I want to kill the Thread which was busy in fetching the Auth Ticket from 3rd party, but got stuck because of some issue. Here is the simplified code.
public String getAuthTicket(final String userName) throws Exception{
String authTicket=null;
final FutureTask<String> future =
new FutureTask<String>(new Callable<String>() {
public String call() throws Exception {
log.info("calling server to get trusted ticket.");
if(Thread.interrupted()){
log.info("Call to server got interrupted.");
return "-1";
}
String authTicket = getTrustedTicket(userName);
return authTicket;
}
});
final Thread thread = new Thread(future);
thread.start();
String authTicket ="-1";
try {
authTicket = future.get(10000, TimeUnit.MILLISECONDS);
log.info("authTicket: "+ authTicket);
return authTicket;
} catch (Exception e){
log.warning("Timeout occured while waiting to get auth ticket: Reason:"+ e);
future.cancel(true);
}
return authTicket;
}
Could anyone please review my code?