In this post under Apache Pool, we will explain with example how to create soft reference object pool.
For our example we will create the below thread factory class that extends Apache Pool framework’s “BasePooledObjectFactory” class.
package package6;
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 package6;
2
3 import org.apache.commons.pool2.impl.SoftReferenceObjectPool;
4
5 public class Example6 {
6 public static void main(String[] args) throws Exception {
7 ThreadPooledObjectFactory threadPooledObjectFactory = new ThreadPooledObjectFactory();
8 SoftReferenceObjectPool<Thread> softReferenceObjectPool = new SoftReferenceObjectPool<Thread>(threadPooledObjectFactory);
9 Thread thread = softReferenceObjectPool.borrowObject();
10 System.out.println(thread.getName());
11 softReferenceObjectPool.returnObject(thread);
12 softReferenceObjectPool.close();
13 }
14 }
In the above code, at line 7, I created an factory instance of “ThreadPooledObjectFactory” class
At line 8, I create an soft reference object pool of type “SoftReferenceObjectPool” and passing the factory instance as constructor argument.
At line 9, I request for a Thread object from the soft reference object pool.
If there is an idle Thread object, it will return that idle Thread object or create a new one.
At line 10, I am printing out the thread name,
At line 11, I am returning the Thread object retrieved at line 9 back to the pool.
At line 12, I close the object pool.
In this way we can create soft reference object pool