In Java 1.4+, there're 3 ways to interrupt a stream which is blocked on socket I/O:
java.net.Socket(InetAddress, int)
constructor, I can close it from a separate thread. As a result, a SocketException
is thrown in the blocked thread.SocketChannel.open(...)
.socket()
(non-blocking I/O) — again, it is possible to close it from a separate thread, but now a different exception (an AsynchronousCloseException
) is thrown in the blocked thread.ClosedByInterruptException
thrown. Interrupting a blocked thread when using old-style Java I/O has no effect on the thread.Questions:
Socket.close()
behaviour when using NIO as opposed to regular IO?Is closing a socket from a separate thread thread-safe when using old-style I/O? If not, what are the alternatives?
yes.
An alternative is to use blocking NIO (which is the default behaviour for a SocketChannel BTW) I prefer this for a small number of connections as it has the efficiency of NIO, but some of the simplicity of Plain IO.
Is closing a socket/channel from a separate thread thread-safe when using NIO instead?
For both blocking NIO, and no blocking NIO, they are thread safe.
Is there any difference in Socket.close() behaviour when using NIO as opposed to regular IO?
If you need to know the details, I suggest you read the code, but basically they are the same.
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)?
How you close a connection is the least of concerns. So yes, there are many reasons to consider NIO over plain IO.
Pros for NIO
Cons
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With