Unfortunately, no, the java.io.*
classes do not respond to interruptions when they are blocked in read or write methods. Typically what you have to do is close the stream and then handle the IOException
that gets thrown. I have this pattern repeated throughout my code:
try {
for (;;) {
try {
inputStream.read(data);
thread.join();
}
catch (IOException exception) {
// If interrupted this isn't a real I/O error.
if (Thread.interrupted()) {
throw new InterruptedException();
}
else {
throw exception;
}
}
}
}
catch (InterruptedException exception) {
}
Alternatively the newer java.nio.*
classes do handle interruptions better and generate InterruptedIOException
s when they are interrupted. Note that this exception is derived from IOException
and not from InterruptedException
so you will probably need two catch
clauses to handle either type of exception, one for InterruptedException
and one for InterrutpedIOException
. And you'll want any inner IOException
catch clause to ignore InterruptedIOException
s.