What causes a "broken pipe", and more importantly, is it possible to recover from that state?
It is caused by something causing the connection to close. (It is not your application that closed the connection: that would have resulted in a different exception.)
It is not possible to recover the connection. You need to open a new one.
If it cannot be recovered, it seems this would be a good sign that an irreversible problem has occurred and that I should simply close this socket connection. Is that a reasonable assumption?
Yes it is. Once you've received that exception, the socket won't ever work again. Closing it is is the only sensible thing to do.
Is there ever a time when this IOException
would occur while the socket connection is still being properly connected in the first place (rather than a working connection that failed at some point)?
No. (Or at least, not without subverting proper behavior of the OS'es network stack, the JVM and/or your application.)
Is it wise to always call SocketChannel.isConnected()
before attempting a SocketChannel.write()
...
In general, it is a bad idea to call r.isXYZ()
before some call that uses the (external) resource r
. There is a small chance that the state of the resource will change between the two calls. It is a better idea to do the action, catch the IOException
(or whatever) resulting from the failed action and take whatever remedial action is required.
In this particular case, calling isConnected()
is pointless. The method is defined to return true
if the socket was connected at some point in the past. It does not tell you if the connection is still live. The only way to determine if the connection is still alive is to attempt to use it; e.g. do a read or write.