Getting number of active and idle objects in object pool

In this post under Apache Pool, I will explain with example how to retrieve number of active and idle objects in object pool.

For our example I will create the below factory class which extends Apache Pool’s “BasePooledObjectFactory” class.

package package5;

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);
}
}

In the above code we created “ThreadPooledObjectFactory” that will create Thread objects on request.

Next we will see the main code

Main class

1  package package5;
2
3 import org.apache.commons.pool2.impl.GenericObjectPool;
4
5 public class Example5 {
6 public static void main(String[] args) throws Exception {
7 ThreadPooledObjectFactory threadPooledObjectFactory = new ThreadPooledObjectFactory();
8 GenericObjectPool<Thread> genericObjectPool = new GenericObjectPool<Thread>(threadPooledObjectFactory);
9
10 Thread Thread1 = genericObjectPool.borrowObject();
11
12 Thread Thread2 = genericObjectPool.borrowObject();
13
14 Thread Thread3 = genericObjectPool.borrowObject();
15
16 System.out.println(genericObjectPool.getNumActive());
17 System.out.println(genericObjectPool.getNumIdle());
18
19 genericObjectPool.returnObject(Thread3);
20
21 System.out.println(genericObjectPool.getNumActive());
22 System.out.println(genericObjectPool.getNumIdle());
23
24 genericObjectPool.close();
25 }
26 }

In the above code, at line 7 we create an instance of “ThreadPooledObjectFactory”.

At line 8, we create an instance of “GenericObjectPool” by passing the “threadPooledObjectFactory” instance as a parameter to constructor.

At line 10, 12, and 14, we request “GenericObjectPool” to create 3 Thread objects if not present and return it to us.

Now at line 16 and 21, we query the number of active objects present in the pool by calling “getNumActive” method on “GenericObjectPool” instance.

Next at line 17 and 22, we query the number of idle objects present in the pool by calling “getNumIdle” method on “GenericObjectPool” instance.

We print those values to the console.

In this way we can get the number of active and idle objects in the pool.

Leave a comment