简体   繁体   中英

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.

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 there can. Though not literally forever :-)

2- Can someone please suggest how we can add timeout for write operation?

You cannot do it with Java's implementation of sockets / SSL sockets, etcetera. Java sockets support connect timeouts and read timeouts but not write timeouts.

See also: How can I set Socket write timout in java?

(Why? Well socket write timeouts were requested in bug ID JDK-4031100 back in 1997 but the bug was closed with status "WontFix". Read the link for the details.)

The alternatives include:

  1. Use a Timer to implement the timeout, and interrupt the thread or close the Socket if the timer goes off. Note that both interrupting and closing will leave you in a state where you need to abandon the socket.

  2. Use NIO selectors and non-blocking I/O.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM