JDK docs say that if a thread is interrupted, which is currently blocked in the interrupt operation, the channel is closed and a ClosedByInterruptException is thrown. However, when using FileChannel, I get a different behavior:
public class Main implements Runnable { public static void main(String[] args) throws Exception { Thread thread = new Thread(new Main()); thread.start(); Thread.sleep(500); thread.interrupt(); thread.join(); } public void run() { try { readFile(); } catch (IOException ex) { ex.printStackTrace(); } } private void readFile() throws IOException { FileInputStream in = new FileInputStream("large_file"); FileChannel channel = in.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(0x10000); for (;;) { buffer.clear();
}
Here, when the thread is interrupted, the read () call returns normally, even if the channel is closed. No exception is thrown. This code prints "thread abort" and "channel closed", and then the next time read () is called, it throws a ClosedChannelException.
I am wondering if this behavior is acceptable. Since I understand the docs, read () should either return normally, or not close the channel, or close the channel, and throw a ClosedByInterruptException. The return is ok and closing the channel seems wrong. The problem for my application is that I get an unexpected and seemingly unbound ClosedChannelException somewhere else when the FutureTask program that does io is canceled.
Note. A ClosedByInterruptException will be thrown as expected when the stream is already interrupted when read () is entered.
I saw this behavior using a 64-bit server VM (JDK 1.6.0 u21, Windows 7). Can anyone confirm this?
source share