In this post under Apache Pool, I will show with example how to create a synchronized object pool.
Below is the complete main class for your reference
Main class
package package16;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PoolUtils;
import org.apache.commons.pool2.impl.GenericObjectPool;
public class StringBufferPoolExample16 {
public static void main(String[] args) {
GenericObjectPool<StringBuffer> genericObjectPool = new GenericObjectPool<StringBuffer>(new StringBufferPooledObjectFactory());
ObjectPool<StringBuffer> threadSafeGenericObjectPool = PoolUtils.synchronizedPool(genericObjectPool);
System.out.println(threadSafeGenericObjectPool);
threadSafeGenericObjectPool.close();
}
}
In the above code, at line 9, We create an instance of “GenericObjectPool” named “genericObjectPool” which is capable of holding “StringBuffer” object in its pool.
At line 10, I create a synchronized version of “genericObjectPool” using “PoolUtils” utitity class static method “synchronizedPool”.
In this way we create an instance of synchronized object pool.