Any problems replacing the new Socket () with SocketChannel.open (). Socket ()?

What could go wrong if I just replaced

socket = new Socket()

      

from

socket = SocketChannel.open().socket()?

      

Background: I have a legacy code with help new Socket()

and I would like to interrupt the call socket.connect()

. I don't want to rewrite the code to use NIO. I found out that it Thread.interrupt()

does not interrupt socket.connect()

, but it is supposed socket.close()

to interrupt the connection on another thread. Oddly enough, this worked with Java 7, but not Java 6.

I somehow figured out that using socket = SocketChannel().open().socket()

would let me use Thread.interrupt()

to interrupt socket.connect()

. It's not, but oddly enough, it does socket.close()

interrupt socket.connect()

in Java 6 too!

Note that I am not using bound, SocketChannel

I am not using in any way --- it appears when I create Socket

and never again.

What could go wrong with this?

+1


source to share


2 answers


There are some.

  • A Socket received through a SocketChannel does not support timeouts.
  • The InputStream and OutputStream of a socket are not independent: they are shared.


Why do you want to interrupt the connect () call? Surely all you want is a connection timeout?

+2


source


Differences in the type of thrown exceptions can break existing code.

For example, closing Socket

from another thread while blocking Socket.getInputStream().read()

will result in an AsynchronousCloseException after replacement instead of from SocketException

which the expected code might have expected. ( AsynchronousCloseException

not a subclass SocketException

.)



However, it Socket.getInputStream().read()

will still throw SocketException

if a close from another thread hits earlier read()

.

0


source







All Articles