suitianshi suitianshi - 13 days ago 4
Android Question

"Socket sharing" in HttpURLConnection implementation

Quote from developer site


To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs. As a result, HTTP connections may be held open longer than necessary.


That means a TCP connection might be shared by multiple HttpURLConnection instances.(also see here).

Suppose I have two separate background threads which is sending a request to the same host through two distinct
HttpURLConnection
. If the underlying Socket is shared between the two connections, data returned by server would be read by two threads at the same time and results in data corruption.

But while I'm testing my Android app, I never encounter this problem. So does that mean the Socket is never shared or am I missing something?

Answer

The statement

To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs.

does not mean that sockets are always reused, it just states that they MAY be reused. If two threads use two URLConnections at the same time, they cannot share a socket as a single socket cannot be used simultanously by multiple threads.

The URLConnection implementation guarantees that a single URLConnection is independent from any other connections in the same runtime environement, so parallel connections cannot reuse their sockets.

However, if one thread closes its URLConnection before the other thread opens its URLConnection, they MAY reuse the existing socket.