What are the advantages/disadvantages of using a Channel
backed Socket
, obtained via SocketChannel.open().socket()
, over a traditional Socket
obtained from new Socket()
?
A similar question three years ago (Any issues with replacing new Socket() with SocketChannel.open().socket()?) touches on this, but much of its information looks outdated. (Tested in Java 8)
My research has found these advantages/disadvantages:
Advantages over new Socket()
Reads on the socket's
InputStream
can be interrupted withThread.interrupt()
, which subsequently also closes the socket and throwsClosedByInterruptionException
. Although it's unfortunate that it closes the socket, I'd have to close it anyway to break out of reads onnew Socket()
and I'd have to separately keep track the socket a thread is bound to.Likewise,
Socket.connect()
can be interrupted withThread.interrupt()
, which also results inClosedByInterruptionException
.Calling
Socket.close()
duringSocket.connect()
results inAsynchronousCloseException
, unlike the crypticSocketException: Socket operation on nonsocket: connect
I get fornew Socket()
.
Advantages over SocketChannel
Reads can be timed out with
Socket.setSoTimeout()
.Can be wrapped in
SSLSocket
(withSSLSocketFactory.createSocket(Socket, ...)
) to do a quick SSL/TLS transition.
Disadvantages over SocketChannel
- Doesn't gain the advantages of using
ByteBuf
to reduce copying during reads or writes, so maybe slower in this sense.
Disadvantages over new Socket()
- ???