Configuring Generic Object Pool

In this post under Apache Pool, I will show how to create GenericObjectPool instance with custom configuration

In all post under Apache Pool, I showed how to create GenericObjectPool using default configuration.

When we use the below code snippet, we are creating an object pool with default configuration.

    GenericObjectPool<Thread> genericObjectPool = new GenericObjectPool<Thread>(threadPooledObjectFactory);

To change the configuration we will take help of “GenericObjectPoolConfig” class as shown below

1  package package7;
2
3 import org.apache.commons.pool2.impl.GenericObjectPool;
4 import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
5
6 public class Example7 {
7 public static void main(String[] args) {
8 GenericObjectPoolConfig<Thread> genericObjectPoolConfig = new GenericObjectPoolConfig<Thread>();
9 genericObjectPoolConfig.setMaxTotal(5);
10 ThreadPooledObjectFactory threadPooledObjectFactory = new ThreadPooledObjectFactory();
11 GenericObjectPool<Thread> genericObjectPool = new GenericObjectPool<Thread>(threadPooledObjectFactory, genericObjectPoolConfig);
12 System.out.println("Max total: " + genericObjectPool.getMaxTotal());
13 genericObjectPool.close();
14 }
15 }

In the above main code, at line 8 we create an instance of “GenericObjectPoolConfig” class.

At line 9 we set maximum number of objects in the pool to 5 by calling “setMaxTotal” method on “genericObjectPoolConfig” instance.

At line 10 I create an instance of “ThreadPooledObjectFactory” class

At line 11, I create an instance of “GenericObjectPool” class.

In all my previous post, whenever I used to create an instance “GenericObjectPool” class I was passing the factory instance as the only constructor argument.

In this case, I will also pass instance “genericObjectPoolConfig” in addition to factory instance “threadPooledObjectFactory”

In this way we can configure an object pool.

Below is the code of “ThreadPooledObjectFactory” for your reference

package package7;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

public class ThreadPooledObjectFactory extends BasePooledObjectFactory<Thread> {
private int count = 0;

@Override
public Thread create() throws Exception {
String threadName = "Thread" + count;
count = count + 1;
return new Thread(threadName);
}

@Override
public PooledObject<Thread> wrap(Thread obj) {
return new DefaultPooledObject<Thread>(obj);
}
}

Leave a comment