Skip to content

Instantly share code, notes, and snippets.

@tirthb
Last active December 15, 2015 06:39
Show Gist options
  • Save tirthb/5217387 to your computer and use it in GitHub Desktop.
Save tirthb/5217387 to your computer and use it in GitHub Desktop.
Recently, I was working towards making a web app more robust. The web app depended on auxiliary API's and databases. I wanted the web app to be operational even without these auxiliary sources. Ajax was not the way to go for SEO reasons. The TimeoutException was taking more than ten seconds to appear. The solution was to implement a single threa…
package any.pack.age;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
public class SomeClass {
private static Logger logger = Logger.getLogger(SomeClass .class);
public Set<Integer> methodCallingAuxiliaryProcess() {
//Making sure application is not affected on Exception
ExecutorService executor = Executors.newSingleThreadExecutor();
//I was expecting a Set<Integer> ids from the service
Future<Set<Integer>> futureIds;
Callable<Set<Integer>> task = new Callable<Set<Integer>>() {
public Set<Integer> call() throws Exception {
//Calling the auxiliary process
callAuxiliaryProcess();
}
};
Set<Integer> ids = null;
long start = System.currentTimeMillis();
try {
futureIds= executor.submit(task);
//Make the timeout period as property, you would require to change it
ids = futureIds.get(10, TimeUnit.SECONDS);
logger.info("Time to get ids " + (System.currentTimeMillis() - start) + " ms.");
} catch (Exception e) {
logger.warn("Could not run auxiliaryProcess " + e, e);
logger.info("Exact timeout to get ids: " + (System.currentTimeMillis() - start) + " ms.");
}
return ids;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment