Clearing ObjectPool of Idle objects

In this post under Apache pool, I will show with example how to clear idle objects from the pool.

For our example lets create a pool with 5 objects and then make 3 out of them idle. I will then show how to clear those 3 idle objects.

Below is the complete main code for your reference

Main class

1  package package12;
2  
3  import org.apache.commons.pool2.impl.GenericObjectPool;
4  
5  public class StringBufferPoolExample12 {
6      public static void main(String[] args) throws Exception {
7          GenericObjectPool<StringBuffer> genericObjectPool = new GenericObjectPool<StringBuffer>(new StringBufferPooledObjectFactory());
8          
9          StringBuffer stringBuffer1, stringBuffer2, stringBuffer3, stringBuffer4, stringBuffer5;
10         stringBuffer1 = genericObjectPool.borrowObject();
11         stringBuffer2 = genericObjectPool.borrowObject();
12         stringBuffer3 = genericObjectPool.borrowObject();
13         stringBuffer4 = genericObjectPool.borrowObject();
14         stringBuffer5 = genericObjectPool.borrowObject();
15 
16         System.out.println("Active Objects in pool: " + genericObjectPool.getNumActive());
17         System.out.println("Idle Objects in pool: " + genericObjectPool.getNumIdle());
18 
19         genericObjectPool.returnObject(stringBuffer4);
20         genericObjectPool.returnObject(stringBuffer5);
21 
22         System.out.println("Active Objects in pool: " + genericObjectPool.getNumActive());
23         System.out.println("Idle Objects in pool: " + genericObjectPool.getNumIdle());
24 
25         genericObjectPool.clear();
26 
27         System.out.println("Active Objects in pool: " + genericObjectPool.getNumActive());
28         System.out.println("Idle Objects in pool: " + genericObjectPool.getNumIdle());
29 
30         genericObjectPool.close();
31     }
32 }

In the above code, I create a pool of StringBuffer objects.

In that pool I create 5 StringBuffer objects and use them. Refer to line 9 to 14.

At line 16 I print number of active objects, which will be 5 at this stage.

At line 17 I print number of idle objects, which in this case will be 0.

Then at line 19 and 20, I return 2 objects back to the pool making them idle.

At line 22, I again print number of active objects, which in this case will be 3.

At line 23, I again print number of idle objects, which in this case will be 2

Then at line 25, I call “clear” method of “GenericObjectPool” class. This will clear all the idle objects from the pool.

At line 27, I print the number of active objects, which will be 3 as usual.

At line 28, I print the number of idle objects, which in this case be 0.

In this way we can clear the idle objects from object pool.

Below is the output

Output

Active Objects in pool: 5
Idle Objects in pool: 0
Active Objects in pool: 3
Idle Objects in pool: 2
Active Objects in pool: 3
Idle Objects in pool: 0

Leave a comment