Editar:
Después de algunas idas y vueltas, parece que usted quiere ser capaz de interrumpir sus rutinas de IO. Esto parece un buen trabajo para algunas de las clases de NIO InterrutibleChannel
. Por ejemplo, leer de la siguiente BufferedReader
es interrumpible y lanzará InterruptedIOException
. Consulte aquí para more examples of the NIO code.
BufferedReader in = new BufferedReader(new InputStreamReader(
Channels.newInputStream((new FileInputStream(
new File(...))).getChannel())));
A continuación, puede llamar future.cancel()
que interrumpirá el hilo y hacer que el IO para lanzar una InterruptedIOException
. Si eso sucede, podría no atrapar el IOException
y dejarlo salir por el método call()
.
Si desea pasar de nuevo a la Future
que el método call()
se interrumpió entonces pienso tirar InterruptedException
está muy bien. Otra opción sería simplemente return null;
u otro objeto marcador de su método call()
. Eso es lo que hago normalmente si se interrumpe un hilo.
Una cosa a tener en cuenta es que si call()
tiros InterruptedException
, cuando se hace una future.get()
va a lanzar una ExecutionException
y la causa de dicha excepción va a ser un InterruptedException
. No se deje confundir que future.get()
también arroje un InterruptedException
sí el get(long timeout, TimeUnit unit)
agota el tiempo.
try {
result = future.get();
} catch (ExecutionException e) {
if (e.getCause() instanceof InterruptedException) {
// call() method was interrupted
}
} catch (InterruptedException e) {
// get was interrupted
}
Si, sin embargo, future.cancel(true)
se llamaba entonces el future.get()
arrojará un CancellationException
lugar.
The One True Source para explicar 'InterruptedException' es [aquí] (http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html). –
Lo leí antes, pero no menciona Incullable. Muy buen artículo, sin embargo. –