javasocketssslblockingsslsocketfactory

Why SSLSocket write option does not have timeout?


In Java, write operation on SSLSocket API is blocking and the write operation does not support timeout also.

Can someone please explain?

  1. Can there be a situation where write operation can block a thread forever? I checked on Internet and it seems that there is a possibility of blocking forever.
  2. How to add timeout for write operation?

My application creates two threads one for read and one for write.


Solution

  • Because:

    1. If such a facility is needed at all, it is needed at the TCP level, not just the SSL level.
    2. There is no API for it at the TCP level, and I don't mean just in Java: there is no C level API for it either, except maybe on a couple of platforms.
    3. If you added it at the SSL level, a write timeout event would leave the connection in an indeterminate state which would mean that it had to be closed, because you couldn't know how much data had been transmitted, so you couldn't maintain integrity at the SSL level.

    To address your specific questions:

    1. Can there be a situation where write operation can block a thread forever? I checked on Internet and it seems that there is a possibility of blocking forever.

    Yes. I've seen an application blocked for several days in such a situation. Although not, as @StephenC rightly says, forever. We haven't lived that long yet.

    1. How to add timeout for write operation?

    You can do it at the TCP level with non-blocking I/O and a Selector, and you can layer an SSLEngine on top of that to get SSL, but it is a tedious and highly error-prone exercise that many have tried: few have succeeded. Not for the faint-hearted.