Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interruptible network I/O in Java

In Java 1.4+, there're 3 ways to interrupt a stream which is blocked on socket I/O:

  1. 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, a SocketException is thrown in the blocked thread.
  2. 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 (an AsynchronousCloseException) is thrown in the blocked thread.
  3. 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:

  1. Is closing a socket from a separate thread thread-safe when using old-style I/O? If not, what are the alternatives?
  2. Is closing a socket/channel from a separate thread thread-safe when using NIO instead?
  3. Is there any difference in Socket.close() behaviour when using NIO as opposed to regular IO?
  4. 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)?
like image 694
Bass Avatar asked Oct 15 '13 11:10

Bass


1 Answers

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

  • Faster and more light weight when using direct memory
  • More scalable to tens of thousands of users.
  • Supports efficient busy waiting.

Cons

  • Plain IO is simpler to code.
  • Many APIs only support plain IO for this reason.
like image 148
Peter Lawrey Avatar answered Sep 29 '22 13:09

Peter Lawrey