Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket vs SocketChannel.open().socket() [duplicate]

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?

like image 247
Robert Tupelo-Schneck Avatar asked Mar 23 '26 11:03

Robert Tupelo-Schneck


1 Answers

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?

like image 159
user207421 Avatar answered Mar 26 '26 13:03

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!