In this post under Apache Pool, I will explain with example the purpose of “addObject” method in Apache Pool.
In Apache Pool we can create three types of object Pool
1) GenericObjectPool
2) GenericKeyedObjectPool
3) SoftReferenceObjectPool
All these classes support “addObject” method.
Now lets understand the purpose of this method.
If you refer to all my previous post, you can see that whenever I need an object from the object pool I used to call “borrowObject” method.
This “borrowObject” method would create a new object if the pool is empty or all the objects present in the pool are currently busy.
So “borrowObject” method only create an object in object pool and allows us to borrow on request.
What if we want to just add an object to object pool and not borrow them.
This is where “addObject” method comes into picture.
It just create and add new objects in object pool.
Below is the main code showing its usage
Main class
1 package package8;
2
3 import org.apache.commons.pool2.impl.GenericObjectPool;
4
5 public class Example8 {
6 public static void main(String[] args) throws Exception {
7 ThreadPooledObjectFactory threadPooledObjectFactory = new ThreadPooledObjectFactory();
8 GenericObjectPool<Thread> genericObjectPool = new GenericObjectPool<Thread>(threadPooledObjectFactory);
9 genericObjectPool.addObject();
10 genericObjectPool.addObject();
11 genericObjectPool.addObject();
12
13 genericObjectPool.close();
14 }
15 }
In the above code, at line 7 we create an instance of “ThreadPooledObjectFactory” class.
At line 8, I create an instance of “GenericObjectPool” class passing the “ThreadPooledObjectFactory” instance as an argument.
At line 9, 10, and 11, I call “addObject” three times as a result of which 3 objects are created and added in object pool.
In this way we can use the “addObject” method.