Any issues with replacing new Socket() with SocketChannel.open().socket()?

こ雲淡風輕ζ 提交于 2019-12-02 10:25:09

问题


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.

  1. A Socket acquired via a SocketChannel doesn't appear to support read timeouts.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!