3

Can any one help me with a sample code of how the URLConnection reuses the connection?

URLConnection con = new URL("http://www.someurl.com").openConnection();

I am using the above code to make a URLConnection. For the first time, the URLConnection will open a new connection to the specified URL. But after that it will reuse the existing connection from the pool. Is there any to prove this (I mean through println()) ?

Actually is there any way to retrieve connection reused status from the pool?

Dilip B S
  • 203
  • 6
  • 15
  • You might be able to "wire sniff" to confirm that it's actually re-using connections. Or check the connection at the server (assuming it uses http keep-alives, that's the only case when it reuses connections I'd imagine...) See also https://stackoverflow.com/q/3304006/32453 – rogerdpack Nov 01 '17 at 21:55

1 Answers1

4

From the java.net.URL javadoc:

Returns a URLConnection object that represents a connection to the remote object referred to by the URL.

A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.

If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

So for a http protocol url it will return a HttpURLConnection

From the java.net.HttpURLConnection javadoc:

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances

So the underlining tcp connection might be pooled

Liviu T.
  • 23,584
  • 10
  • 62
  • 58
  • Okay. Agreed. But is it possible to prove it? It would be very much helpful if you provide a sample code to prove the tcp connection being pooled and reused. – Dilip B S Nov 25 '11 at 09:05
  • @Dilip B S It isn't possible to prove it from code, that's how completely it's engineered to be hidden under the hood. You would have to sniff the network. – user207421 Nov 25 '11 at 09:32
  • hmmm:) But it seems just conceptual. So perhaps there could be a way to prove it... We rely on the java doc. If the requirement is to prove it, then we have to. – Dilip B S Nov 25 '11 at 10:04
  • hmm having to prove that a programming language base library does what is says is a little strange. Is it more related to having to profile a certain method for network traffic? – Liviu T. Nov 25 '11 at 10:14
  • :-) But my requirement is that... Anyway thanks for the response – Dilip B S Nov 25 '11 at 12:04