Search code examples
javaconnectionpool

Creation of url connection pool in java


I have some code like this in a method :

        URL url = new URL(endPoint);
        String encoding = Base64.encodeBase64String(this.key.getBytes());

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty  ("Authorization", "Basic " + encoding);

This method is called many times from the client side. I wish I could create a connection pool and reuse the same as needed.

Is it possible to do so in Java?

Thanks in advance


Solution

  • Pooling HTTP connection is similar to other pooling object.

    Basically :

    • use a factory to get an instance of your HTTP connections
    • dont forget to release it, via the factory, to your pool when no more used
    • in your pool management don't forget to check and close your connections.

    I don't advise you to re-code all pool management, but rather use existing librairies like Jakarta Commons-pool.

    Jakarta Commons-pool enable you :

    • to reject immediatly demand of new HTTP connection with a "pool exhausted exception"
    • to increase pool size despite his limits
    • to wait during N ms, expecting a free HTTP connection (exception after delay).