In this post under Apache Pool, I will explain with example the purpose of “getBorrowedCount” method.
This method is mainly used when generating statistics of a particular object pool.
This method returns the total number of objects borrowed from the 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 pool, the result of “getBorrowedCount” method will be 10.
Below is the main class showing its usage.
Main class
package package13;
import org.apache.commons.pool2.impl.GenericObjectPool;
public class StringBufferPoolExample13 {
public static void main(String[] args) {
GenericObjectPool<StringBuffer> genericObjectPool = new GenericObjectPool<StringBuffer>(new StringBufferPooledObjectFactory());
StringBuffer stringBuffer1 = null, stringBuffer2 = null;
try {
stringBuffer1 = genericObjectPool.borrowObject();
stringBuffer2 = genericObjectPool.borrowObject();
System.out.println("Borrowed Count: " + genericObjectPool.getBorrowedCount());
} catch(Exception exception) {
exception.printStackTrace();
} finally {
if(stringBuffer1 != null) {
genericObjectPool.returnObject(stringBuffer1);
}
if(stringBuffer2 != null) {
genericObjectPool.returnObject(stringBuffer2);
}
genericObjectPool.close();
}
}
}
In the above code, we borrowed “StringBuffer” object twice from the pool, refer line 11 and 13.
So the line 15 will print “2” to the console.
In this way we can use “getBorrowedCount” method.