Java -- Object Pooling technology org. apache. commons. pool2.ObjectPool, apachecommonspool
Org. apache. commons. pool2.ObjectPool provides an object pool, which can be directly used by developers to build an object pool.
There are two simple steps to use this object pool:
1. Create an object factory. org. apache. commons. pool2.BasePooledObjectFactory has an abstract Implementation of the factory, so you only need to inherit this class and implement the template method.
Package com. seeyon. objectPool; import org. apache. commons. pool2.BasePooledObjectFactory; import org. apache. commons. pool2.PooledObject; import org. apache. commons. pool2.impl. defaultPooledObject;/*** Created by yangyu on 16/12/26. * // *** object factory, used to create an object */public class ObjectFactory extends BasePooledObjectFactory <ObjectFactory. computer> {/*** create an object and return the desired object instance * @ return * @ throws Exception */@ Override public Computer create () throws Exception {return new Computer ("mac");}/*** wrap object, wrap the object as PooledObject * @ param obj * @ return */@ Override public PooledObject <Computer> wrap (Computer obj) {return new DefaultPooledObject <> (obj );} public class Computer {String name; public Computer (String name) {this. name = name ;}}}
2. Use the object pool
Package com. seeyon. objectPool; import org. apache. commons. pool2.ObjectPool; import org. apache. commons. pool2.impl. genericObjectPool;/*** Created by yangyu on 16/12/26. * // *** org. apache. commons. use of pool2.ObjectPool Object pool * directly use apache Object pool to implement object Pooling technology */public class TestObjectPool {public static void main (String [] args) throws InterruptedException {/*** create object factory */ObjectFactory objectFactory = new ObjectFactory ();/*** create a common object pool */ObjectPool <ObjectFactory. computer> objectPool = new GenericObjectPool (objectFactory);/*** create the first Thread */Thread t1 = new Thread (() -> {try {/*** get the object from the object pool */ObjectFactory. computer computer = objectPool. borrowObject (); System. out. println (Thread. currentThread (). getId () + ":" + computer);/*** put the object back into the object pool after use */objectPool. returnObject (computer);} catch (Exception e) {e. printStackTrace () ;}}); t1.start (); t1.join (); new Thread ()-> {try {/*** get the object from the object pool again, you will find that the same object is obtained, indicating that the object Pooling technology is successful */System. out. println (Thread. currentThread (). getId () + ":" + objectPool. borrowObject ();} catch (Exception e) {e. printStackTrace ();}}). start ();}}
3. output result: the same object is used after the two threads start from the beginning, and pooled technology is used.
11:com.seeyon.objectPool.ObjectFactory$Computer@4e72fd412:com.seeyon.objectPool.ObjectFactory$Computer@4e72fd4