In Java 1.4+, there're 3 ways to interrupt a stream which is blocked on socket I/O:
- If the socket was created using a regular
java.net.Socket(InetAddress, int)
constructor, I can close it from a separate thread. As a result, aSocketException
is thrown in the blocked thread. - If the socket was created using
SocketChannel.open(...)
.socket()
(non-blocking I/O) — again, it is possible to close it from a separate thread, but now a different exception (anAsynchronousCloseException
) is thrown in the blocked thread. - Additionally, in case non-blocking I/O is used, it is possible to interrupt a blocked thread, with a
ClosedByInterruptException
thrown. Interrupting a blocked thread when using old-style Java I/O has no effect on the thread.
Questions:
- Is closing a socket from a separate thread thread-safe when using old-style I/O? If not, what are the alternatives?
- Is closing a socket/channel from a separate thread thread-safe when using NIO instead?
- Is there any difference in
Socket.close()
behaviour when using NIO as opposed to regular IO? - Are there any benefits of using NIO for networking other than a possibility to terminate a blocked I/O operation by simply interrupting a thread (so that I no longer need to keep a reference to the socket)?