Home  Java   Connection ...

Connection pooling example in Java

Let’s go through connection pooling in HTTP clients with a clear example. I’ll explain what it is first, then show OkHttp and Apache HttpClient examples.


1️⃣ What is connection pooling?

✅ Benefits:


2️⃣ OkHttp Connection Pool Example

OkHttp has built-in connection pooling. By default, it keeps 5 idle connections alive for 5 minutes, but you can configure it.

import okhttp3.*;

import java.util.concurrent.TimeUnit;

public class OkHttpPoolingExample {
    public static void main(String[] args) throws Exception {
        // Custom connection pool: 10 connections, 10 minutes idle timeout
        ConnectionPool pool = new ConnectionPool(10, 10, TimeUnit.MINUTES);

        OkHttpClient client = new OkHttpClient.Builder()
                .connectionPool(pool)
                .build();

        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Send multiple requests reusing the same connections
        for (int i = 0; i < 5; i++) {
            Response response = client.newCall(request).execute();
            System.out.println(response.code() + " - " + response.body().string());
        }
    }
}

What happens internally:


3️⃣ Apache HttpClient Connection Pool Example

Apache HttpClient has an explicit connection manager to manage a pool of connections.

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ApachePoolingExample {
    public static void main(String[] args) throws Exception {
        // Create a connection manager with pooling
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(20);        // max total connections
        cm.setDefaultMaxPerRoute(5); // max per host

        CloseableHttpClient client = HttpClients.custom()
                .setConnectionManager(cm)
                .build();

        HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");

        for (int i = 0; i < 5; i++) {
            HttpResponse response = client.execute(request);
            System.out.println(response.getStatusLine().getStatusCode() + " - " +
                    EntityUtils.toString(response.getEntity()));
        }

        client.close();
    }
}

Key points:


Published on: Oct 05, 2025, 11:44 PM  
 

Comments

Add your comment