Interruptible network I/O in Java

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.