ObjectPool getReturnedCount example

In this post under Apache Pool, I will explain with example the purpose of “getReturnedCount” method.

This method is mainly used when generating statistics of a particular object pool.

This method returns the total number of objects returned back to pool during the lifetime of the pool.

So for example, if we have pool running for 1 hour and during that time we requested 10 objects from the empty pool, it will create 10 objects, and if we return two object, the value of “getReturnedCount” will be 2.

Below is the main class showing its usage.

Main Class

package package15;

import org.apache.commons.pool2.impl.GenericObjectPool;

public class StringBufferPoolExample15 {
    public static void main(String[] args) {
        GenericObjectPool<StringBuffer> genericObjectPool = new GenericObjectPool<StringBuffer>(new StringBufferPooledObjectFactory());

        StringBuffer stringBuffer1 = null, stringBuffer2 = null, stringBuffer3 = null;
        try {
            stringBuffer1 = genericObjectPool.borrowObject();

            stringBuffer2 = genericObjectPool.borrowObject();

            stringBuffer3 = genericObjectPool.borrowObject();

            genericObjectPool.returnObject(stringBuffer1);

            genericObjectPool.returnObject(stringBuffer2);

            System.out.println("Returned Count: " + genericObjectPool.getReturnedCount());
        } catch(Exception exception) {
            exception.printStackTrace();
        } finally {
            if(stringBuffer3 != null) {
                genericObjectPool.returnObject(stringBuffer3);
            }
            genericObjectPool.close();
        }
    }
}

In the above code, we start with an empty pool and borrow 3 objects.

Since the object pool is empty it will create 3 objects.

Then we return back 2 objects to the pool. Refer to line 17 and 19.

The output of “getReturnedCount” will 2, which will be printed to the console.

In this way we can use “getReturnedCount” method

Leave a comment