Backend Development 8 min read

Using Apache Commons Pool for Object Pooling and Jedis Connection Pool in Java

The article explains how to use Apache Commons Pool to create reusable object pools in Java—showing Maven setup, a custom PooledObjectFactory, pool configuration, borrowing and returning objects, and demonstrates a Redis Jedis connection pool built on the same framework while detailing the pool’s initialization, borrowing, and return mechanisms.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Using Apache Commons Pool for Object Pooling and Jedis Connection Pool in Java

When creating or destroying resource objects is time‑consuming, pooling techniques can be used to reuse those resources, reduce system overhead, and increase throughput. Typical examples include database connection pools, thread pools, and Redis connection pools.

Apache Commons Pool provides a generic object‑pool implementation that manages and reuses objects to improve performance and resource utilization.

1. Basic Usage

1.1 Add Maven Dependency

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.0</version>
</dependency>

1.2 Define an Object Factory

The PooledObjectFactory interface defines methods for creating, activating, passivating, validating, and destroying pooled objects.

public interface PooledObjectFactory
{
    /** Creates an instance that can be served by the pool and wrap it in a */
    PooledObject
makeObject() throws Exception;

    /** Destroys an instance no longer needed by the pool */
    void destroyObject(PooledObject
p) throws Exception;

    /** Ensures that the instance is safe to be returned by the pool */
    boolean validateObject(PooledObject
p);

    /** Reinitializes an instance to be returned by the pool */
    void activateObject(PooledObject
p) throws Exception;

    /** Uninitializes an instance to be returned to the idle object pool */
    void passivateObject(PooledObject
p) throws Exception;
}

Example object to be pooled

public class MyObject {
    private String uid = UUID.randomUUID().toString();
    private volatile boolean valid = true;

    public void initialize() {
        System.out.println("初始化对象" + uid);
        valid = true;
    }

    public void destroy() {
        System.out.println("销毁对象" + uid);
        valid = false;
    }

    public boolean isValid() { return valid; }
    public String getUid() { return uid; }
}

Factory implementation for MyObject

public class MyObjectFactory implements PooledObjectFactory
{
    @Override
    public PooledObject
makeObject() throws Exception {
        MyObject object = new MyObject();
        object.initialize();
        return new DefaultPooledObject<>(object);
    }

    @Override
    public void destroyObject(PooledObject
p) throws Exception {
        p.getObject().destroy();
    }

    @Override
    public boolean validateObject(PooledObject
p) {
        return p.getObject().isValid();
    }

    @Override
    public void activateObject(PooledObject
p) throws Exception { }

    @Override
    public void passivateObject(PooledObject
p) throws Exception { }
}

1.3 Configure the Object Pool

GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(20);
config.setMaxIdle(5);
config.setTestWhileIdle(true);
config.setMinEvictableIdleTimeMillis(60000L);
GenericObjectPool
pool = new GenericObjectPool<>(new MyObjectFactory(), config);

1.4 Borrow and Return Objects

MyObject myObject = null;
try {
    myObject = pool.borrowObject();
    System.out.println("get对象" + myObject.getUid() + " thread:" + Thread.currentThread().getName());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (myObject != null) {
            pool.returnObject(myObject);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2. Jedis Connection Pool

Jedis is a Java client for Redis. Its internal connection management relies on Commons Pool. The following example creates a Jedis pool using version 3.3.0.

public class JedisMain {
    public static void main(String[] args) throws Exception {
        // Create pool configuration
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(100);
        config.setMaxIdle(20);
        // Create the pool
        JedisPool pool = new JedisPool(config, "localhost", 6379);
        // Get a connection
        Jedis jedis = pool.getResource();
        jedis.set("hello", "张勇");
        String value = jedis.get("hello");
        System.out.println(value);
        // Return the connection
        jedis.close();
        Thread.sleep(5000);
    }
}

The JedisFactory implements the four core methods of the PooledObjectFactory : create, destroy, validate (via ping ), and activate.

3. Principle Analysis of GenericObjectPool

3.1 Initialization

public GenericObjectPool(final PooledObjectFactory
factory,
                         final GenericObjectPoolConfig
config) {
    super(config, ONAME_BASE, config.getJmxNamePrefix());
    if (factory == null) {
        jmxUnregister();
        throw new IllegalArgumentException("factory may not be null");
    }
    this.factory = factory;
    idleObjects = new LinkedBlockingDeque<>(config.getFairness());
    setConfig(config);
}

private final Map
, PooledObject
> allObjects =
        new ConcurrentHashMap<>();

Initialization performs three tasks: create the factory, create the storage containers ( idleObjects and allObjects ), and set pool properties.

3.2 Borrowing Objects

The borrowObject method first tries to fetch an idle object; if none exists, it creates a new one via the factory, activates it, validates it, and then returns it.

3.3 Returning Objects

When returning, the pool may validate the object, destroy it if validation fails, or discard it if the idle pool is full; otherwise the object is placed back into idleObjects .

JavaBackend DevelopmentRedisConnection PoolJedisObject PoolingApache Commons Pool
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.