Interrupt Closes Blocking Channels
A blocked channel read on a socket responds to interrupt by closing the channel and raising ClosedByInterruptException instead of returning.
Code
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class InterruptibleRead {
public static void main(String[] args) throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress("127.0.0.1", 0)); // port 0: ephemeral
SocketChannel client = SocketChannel.open(server.getLocalAddress());
SocketChannel accepted = server.accept(); // peer stays silent, read blocks
Thread reader = new Thread(() -> {
try {
client.read(ByteBuffer.allocate(64));
System.out.println("read returned: unexpected");
} catch (ClosedByInterruptException closed) {
System.out.println("interrupt closed the channel");
}
});
reader.start();
Thread.sleep(100);
reader.interrupt(); // a blocking read on an interruptible channel wakes up
reader.join(1000);
System.out.println("client still open: " + client.isOpen());
client.close();
accepted.close();
server.close();
}
}Reading the code — Interrupt Closes Blocking Channels
Interrupt Closes Blocking Channels is built around the class InterruptibleRead.
Watch out for
- Drop the file into a project as-is — no additions are required first.
Using it
Each pass stamps the console with: read returned: unexpected, interrupt closed the channel, client still open: — when the file runs.
Key statements
Thread reader = new Thread(() -> {
try {
client.read(ByteBuffer.allocate(64));
System.out.println("read returned: unexpected");
} catch (ClosedByInterruptException closed) {
System.out.println("interrupt closed the channel");
}
});
Thread.sleep(100);
Interactive Tools for This Topic
FAQ
- What does Interrupt Closes Blocking Channels print when run?
- Invoke the file as-is — the `read returned: unexpected`, `interrupt closed the channel`, `client still open:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.