Je me sens l'approche en réponse acceptée est un peu vieillot. Avec Java8, cela peut être fait beaucoup plus simple.
Dites, vous avez une méthode
MyResult conjureResult(String param) throws MyException { ... }
alors vous pouvez le faire (continuez à lire, c'est juste pour montrer l'approche):
private final ExecutorService timeoutExecutorService = Executors.newSingleThreadExecutor();
MyResult conjureResultWithTimeout(String param, int timeoutMs) throws Exception {
Future<MyResult> future = timeoutExecutorService.submit(() -> conjureResult(param));
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
}
bien sûr, jeter exception est mauvais, voici la version étendue correcte avec le traitement des erreurs correctes, mais je vous suggère de l'examiner attentivement, vous voudrez peut-être faire certaines choses différemment (enregistrement, retour du délai dans le résultat étendu, etc.):
private final ExecutorService timeoutExecutorService = Executors.newSingleThreadExecutor();
MyResult conjureResultWithTimeout(String param, int timeoutMs) throws MyException {
Future<MyResult> future = timeoutExecutorService.submit(() -> conjureResult(param));
try {
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
//something interrupted, probably your service is shutting down
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
//error happened while executing conjureResult() - handle it
if (e.getCause() instanceof MyException) {
throw (MyException)e.getCause();
} else {
throw new RuntimeException(e);
}
} catch (TimeoutException e) {
//timeout expired, you may want to do something else here
throw new RuntimeException(e);
}
}
Super! Travaillé parfait pour moi. – Haych