问题
What can go wrong if I simply replace
socket = new Socket()
with
socket = SocketChannel.open().socket()?
Background: I have some legacy code using new Socket()
, and I wanted to be able to interrupt the socket.connect()
call. I don't want to rewrite the code to use NIO. I learned that Thread.interrupt()
does not interrupt socket.connect()
, but that socket.close()
on another thread is supposed to interrupt the connection. Oddly, that worked with Java 7 but not Java 6.
I somehow got it into my head that using socket = SocketChannel().open().socket()
would magically allow me to use Thread.interrupt()
to interrupt socket.connect()
. It doesn't, but oddly, it does make socket.close()
interrupt socket.connect()
in Java 6 too!
Note that I'm not directly using the attached SocketChannel
in any way---it appears when I create the Socket
and never again.
What can go wrong with this?
回答1:
There are several.
- A Socket acquired via a SocketChannel doesn't appear to support read timeouts.
- The InputStream and OutputStream of a socket aren't independent: they have a mutual lock in common.
Why do you want to interrupt the connect() call? Surely all you want is a connect timeout?
回答2:
Differences in the type of thrown exceptions could break existing code.
For instance, closing a Socket
from a different thread while Socket.getInputStream().read()
is blocking will result in AsynchronousCloseException after replacing, instead of SocketException
that legacy code could be expecting. (AsynchronousCloseException
is not a subclass of SocketException
.)
However, Socket.getInputStream().read()
will still throw SocketException
if the close from the other thread gets in before read()
.
来源:https://stackoverflow.com/questions/19775628/any-issues-with-replacing-new-socket-with-socketchannel-open-socket