Add timeout to prevent spending forever trying to determine an Internet connection

This commit is contained in:
drdev
2014-08-25 22:43:56 +00:00
parent acf3aa6693
commit cb7ff871dd
2 changed files with 34 additions and 4 deletions

View File

@@ -45,4 +45,21 @@ public class ThreadUtil {
public static boolean isGameThread() {
return Thread.currentThread().getName().startsWith("Game");
}
public static <T> T executeWithTimeout(Callable<T> task, int milliseconds) {
ExecutorService executor = Executors.newCachedThreadPool();
Future<T> future = executor.submit(task);
T result;
try {
result = future.get(milliseconds, TimeUnit.MILLISECONDS);
}
catch (Exception e) { //handle timeout and other exceptions
e.printStackTrace();
result = null;
}
finally {
future.cancel(true);
}
return result;
}
}