Monday, January 28, 2013

Timeout an api call using executors




import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ApiTimeout {

public static void main(String[] args) {
Library library = new Library();
for (;;) {
String value = library.servicesMethod();
System.out.println("Got the value [" + value + "]");
}
}
}

class Library {
// create executor pool of timing threads

Api2 nApi = new Api2();
Api1 gApi = new Api1();

private static final ExecutorService exService = Executors.newCachedThreadPool();

public String servicesMethod() {
// get thread from pool
Callable<String> task = new Callable<String>() {
public String call() {
return gApi.method();
}
};

// make timed api call
Future<String> future = exService.submit(task);

String result = null;
try {
result = future.get(50, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
// if the call takes to long fall back
result = nApi.method();
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(true); // may or may not desire this
}
return result;
}

}
class Api1 {
public String method() {
try {
Thread.sleep(50);
} catch (InterruptedException ignore) {

}
return "Api1 called()";
}
}

class Api2 {
public String method() {
return "Failed over to Api2 call()";
}
}