Socket vs SocketChannel.open().socket()

73 views Asked by At

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 with Thread.interrupt(), which subsequently also closes the socket and throws ClosedByInterruptionException. Although it's unfortunate that it closes the socket, I'd have to close it anyway to break out of reads on new Socket() and I'd have to separately keep track the socket a thread is bound to.

  • Likewise, Socket.connect() can be interrupted with Thread.interrupt(), which also results in ClosedByInterruptionException.

  • Calling Socket.close() during Socket.connect() results in AsynchronousCloseException, unlike the cryptic SocketException: Socket operation on nonsocket: connect I get for new Socket().

Advantages over SocketChannel

  • Reads can be timed out with Socket.setSoTimeout().

  • Can be wrapped in SSLSocket (with SSLSocketFactory.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()

  • ???
0

There are 0 answers