me siento el enfoque en respuesta aceptada es un poco anticuado. Con Java8, se puede hacer mucho más simple.
Diga, usted tiene un método
MyResult conjureResult(String param) throws MyException { ... }
entonces usted puede hacer esto (seguir leyendo, esto es sólo para mostrar el enfoque):
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);
}
por supuesto, lanzando excepción es malo, aquí está la versión extendida correcta con el procesamiento correcto de errores, pero le sugiero que la examine cuidadosamente; es posible que desee hacer algunas cosas de manera diferente (registro, tiempo de espera excedido en resultado extendido, 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);
}
}
¡Genial! Trabajado perfeccionado para mí. – Haych