3 ms·
Thread interrupts are a purely Java thing [1]. Probably when the blocking operation detects that the interrupt flag is set, they cancel the internally asynchron
by layer8 4y ago
Thread interrupts are a purely Java thing [1]. Probably when the blocking operation detects that the interrupt flag is set, they cancel the internally asynchronous operation, but can’t do so on all platforms without also closing the channel.
You should still be able to share FileChannels between threads when all immediate client code is under your control so you can handle that situation gracefully.
[1] It’s just a flag you can set on a thread, requesting the thread to stop its operation (the thread is not required to comply), and longer-running operations like I/O can choose to test that flag, and typically throw some exception when it is set. The default exception type for this is InterruptedException, but here they chose to throw a subclass of IOException, probably exactly because it also closes the channel.
- twic 4y agoThis is it - a thread that's blocked on I/O won't see the interrupt flag until the system call returns, so interrupting it also closes the file descriptor, to force the system call to return straight away. It's a nasty kludge. I wonder if the virtual threads from Project Loom could let the JVM do the right thing here, and interrupt the virtual thread without waiting for the carrier thread to return from the system call. That might be extremely hairy, though - your thread could return from a read call with an InterruptedException, and then some time later, the data from the read could end up in your buffer as if by magic!