Prateek
Prateek

Reputation: 12242

Is there any way for doing http connection pooling?

Is there any way in java to do http connection pooling without using third party api like httpclient,http-commons etc..?

In my case i want to open a connection with url of particular servlet & my query string changes but whenever i open a connection.it open a new connection as i have seen doing 'netstat -anp | grep portno' which i dont want ?

String sendMessageUrl="http\://ip\:portno/contextpath/servlet/Servletname?parameter1\=&parameter2\=";
URL testURl=new URL(sendMessageUrl.replaceAll("&", name+"&")+surname);  
HttpURLConnection httpConnection=(HttpURLConnection)testURl.openConnection();
httpConnection.connect();
if(httpConnection.getResponseCode()==200)
{
   System.out.println("Success");
}

Here only parameter1 & parameter2 changes except that entire url remains same.

Upvotes: 1

Views: 5454

Answers (2)

Cratylus
Cratylus

Reputation: 54074

You can use HttpURLConnection part of JDK. It uses a TCP connection pool under the hood

Upvotes: 1

ramsinb
ramsinb

Reputation: 2005

You pool objects when it is expensive to create those objects, for example database connections are expensive to create and therefore pooling makes sense. Without using a third party framework it's still possible to pool HTTP connections, after all a pool is simply a collection of previously created instances of a class.

At a minimum to create a class that manages connection pooling for HTTP you'll at least need to do the following:

  1. Retrieve an instance from the pool (object in use)
  2. Place the instance back in the pool (object no longer in use)
  3. Size of pool

You might also need to look at the following as functionality that might be worthwhile on the pool:

  1. Reconnect instances that have become stale
  2. Maximum idle time, remember an idle connection is still consuming resources
  3. Time a connection can be in use before throwing an exception
  4. A way to validate the connection is valid, e.g. For a db connection a simple SQL is executed

There are many other things to consider however it depends on your exact requirements if your building it yourself. You should try it out and if you run into problems then ask SO for help on your specific issues.

Upvotes: 2

Related Questions