0

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?

Community
  • 1
  • 1
suitianshi
  • 3,300
  • 1
  • 17
  • 34

1 Answers1

1

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.

Tobias
  • 7,723
  • 1
  • 27
  • 44
  • So if I have 20 threads requesting at the same time, I have at least 20 distinct TCP connections in the runtime? The http rfc says that the client should not have more than 2 connections to the same host. – suitianshi Jan 12 '16 at 08:57
  • Correct, unless you enforce your own restrictions, Java will happily create more TCP connections. What did you expect? Should a `URLConnection` block until less than two other `URLConnection`s are connected to the same host? Such recommendations should be implemented in the program and / or server, not in the standard library. – Tobias Jan 12 '16 at 09:10