Markus A. Markus A. - 2 months ago 5x
Java Question

Is the SocketChannel returned by ServerSocketChannel.accept() guaranteed to be connected?

This is a pretty basic question, but I can't find a definitive answer for it anywhere:

When I accept() a connection from a ServerSocketChannel, am I guaranteed that the returned SocketChannel is "connected", or could it happen that the returned channel is still performing some form a handshake or whatever and will only later set its


In other words, am I guaranteed that the following piece of code will never print

ServerSocketChannel serverSocketChannel =;
serverSocketChannel.socket().bind(new InetSocketAddress(1234));
SocketChannel socketChannel = serverSocketChannel.accept();


According to the source of ServerSocketChannelImpl the ServerSocketChannelImpl creates a SocketChannelImpl with a state of ST_CONNECTED.

Since the SocketChannelImpl.isConnected() method checks for a state of ST_CONNECTED, your test should always return true.

That is however the scenario for the good times. What could happen is that your server thread gets delayed and by the time your thread calls isConnected() the client already closed the connection.

So, no, there is no guarantee that your code will never print false.