Intermittent network I / O in Java

In Java 1.4+, there are 3 ways to interrupt a thread that is blocked on I / O sockets:

Questions:

  • Closes a socket from a separate thread thread-safe when using old-style I / O? If not, what are the alternatives?
  • Closes a socket / channel from a separate stream thread-safe when using NIO instead?
  • Is there a difference in Socket.close() when using NIO as opposed to regular I / O?
  • Are there any advantages to using NIO for networking, other than the ability to shut down blocked I / O by simply interrupting the stream (so that I no longer need to refer to the socket)?
+6
source share
2 answers

Closes 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 NIO lock (which is the default behavior for SocketChannel BTW). I prefer this for a small number of compounds since it has NIO efficiency, but some of the simplicity of Plain IO.

Closes a socket / channel from a separate stream thread-safe when using NIO instead?

For NIO locks and without NIO locks, they are thread safe.

Is there a difference in the behavior of Socket.close () 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 advantages to using NIO for networking, other than the ability to shut down blocked I / O by simply interrupting the flow (so that I no longer need to refer to the socket)?

As you close the connection, this is the least problem. So yes, there are many reasons to consider NIO compared to regular IO.

Pros for NIO

  • Faster and lighter weight when using direct memory
  • More scalable to tens of thousands of users.
  • Supports effective expectation of expectation.

vs

  • Normal IO is easier to code.
  • For this reason, many APIs support only simple IO.
+3
source

1) Since the main OS call error that throws an exception comes from the TCP stack, which is multi-threaded, there should not be any problems.

2) Not sure - I have not tried it, but would be surprised if there was a problem.

3) Some differences in performance are possible. Calling OS close () requires a 4-way handshake with a TCP host - they are not sure which OS supports this in a non-blocking way (the same with communication).

4) Thread..or connector. You must keep a link to something. Since you are closing the socket, it seems reasonable to keep a link to it :)

0
source

Source: https://habr.com/ru/post/955980/


All Articles