Commons-pool Source Code Analysis Summary

Source: Internet
Author: User

Regardless of the procedure or the framework of the source code analysis, always based on the use of it, when we use it, then there will be curiosity and motivation to analyze how it is implemented.

There are very few programmers who use Commons-pool directly, but they are often used in our projects. How did I get into contact with Commons-pool? This is when I learned Java EE development, when the time needed to use DBCP as a database connection pool, but DBCP relies on commons-pool to cache connection, I am a like to study the people, and like to have a deep understanding of something, Then it will play its role to the maximum.

What features does the 1.commons-pool provide?

Starting with the previous mention of COMMONS-DBCP using Commons-pool, why would commons-dbcp use it?

COMMONS-DBCP provides developers with a pool of available database connections, as the name implies COMMONS-DBCP caches many database connections. Is this caching feature implemented in DBCP? No, in fact, dbcp in the database of the function of the cache is commons-pool to provide, which also shows that Commons-pool has the function of the cache object.

Why do I need to cache objects? This is because the creation and release of objects is a time-consuming and space-intensive process, and any program or user that uses the object waits for a long time if it is just the object that is being created. This is especially important for applications that require frequent creation and destruction of certain types of objects, or that require frequent access to modifications (the entire process is based on reusable objects , of course).

2. Fundamentals of Caching

Now that the Commons-pool provides the object cache functionality, what is object caching and what is caching? We know that the process of creating objects is to allocate memory space, object initialization, object registration to the number of objects, return object references, and so on. If the object is not cached, then each time an object needs to go through the above steps, if such operations are more frequent, it will greatly reduce the performance of the program.

3. Implementation of the Commons-pool cache
    • Generic Programming in Commons-pool
      In Java, if you want to make a program or a framework reusable, then generic programming is necessary. Generic programming the so-called meaning is that the program or the type of object that the framework targets is not explicitly limited, for example, the hashmap that people often use
 Public  class HashMap<k,V> extends abstractmap<k ,v> implements Map<K,v;, cloneable , Serializable {    Private Static Final LongSerialversionuid =362498820763181265L/ * * Implementation notes. *     /     ......

The K and V in the above HashMap do not explicitly specify the type of K and V, which allows the hashmap to use a variety of base data types or a custom class as its K or V. This gives the HashMap a more flexible use.

And in the Commons-pool, it's

// 对象工厂类(T为对象的类型)publicinterface PooledObjectFactory<T> {  // 创建一个对象(T为对象的类型)   PooledObject<T> makeObject() throws Exception;  // 销毁一个对象(T为对象的类型)   void destroyObject(PooledObject<T> p) throws Exception;  ......

Here is a small example

Userinfo.java This is the type of object we need to cache

 PackageMh.test; Public  class UserInfo {    PrivateString name;Private intAge Public UserInfo() {//TODO auto-generated constructor stub} Public UserInfo(String name,intAge) {//TODO auto-generated constructor stub         This. name = name; This. Age = Age; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; }@Override     PublicStringtoString() {//TODO auto-generated method stub        return "User name:"+ This. name+", Age:"+ This. Age; }}

Userfactory.java the production plant of the cache object must inherit the Commons-pool factory class

Package Mh.test;import Org.apache.commons.pool2.pooledobject;import org.apache.commons.pool2.PooledObjectFactory; Import Org.apache.commons.pool2.impl.DefaultPooledObject; Public classUserfactory implements pooledobjectfactory<userinfo>{@Override PublicPooledobject<userinfo>Makeobject() throws Exception {//TODO auto-generated method stubSystem. out. println ("Create a new object");return NewDefaultpooledobject<userinfo> (NewUserInfo ()); } @Override Public void Destroyobject(Pooledobject<userinfo> p) throws Exception {//TODO auto-generated method stubUserInfo user = P.getobject (); System. out. println ("Destroy Object"+user.tostring ()); user =NULL; } @Override PublicBooleanValidateobject(Pooledobject<userinfo> p) {//TODO auto-generated method stub        if(P.getobject () instanceof UserInfo) {System. out. println ("is a legitimate object.");return true; } System. out. println ("is an illegal object.");return false; } @Override Public void Activateobject(Pooledobject<userinfo> p) throws Exception {//TODO auto-generated method stubSystem. out. println ("Reinitialize Object"); } @Override Public void Passivateobject(Pooledobject<userinfo> p) throws Exception {//TODO auto-generated method stubUserInfo user = P.getobject (); System. out. println ("The object has been returned:"+user.tostring ()); }}

Testpool. How Java uses Commons-pool

 PackageMh.test;ImportOrg.apache.commons.pool2.impl.GenericObjectPool; Public  class testpool {    /** * @param args * *     Public Static void Main(string[] args) {//TODO auto-generated method stubGenericobjectpool<userinfo> pool =NewGenericobjectpool<userinfo> (NewUserfactory ());Try{UserInfo user = Pool.borrowobject (); User.setage (Ten); User.setname ("MH");            System.out.println (User.tostring ());        Pool.returnobject (user); }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); }    }}
    • Commons-pool Working principle Analysis

In fact, Commons-pool's working principle is very simple, generic + Factory mode + cache linked list. Generics, which allows the framework to cache multiple object types; Factory mode, the user inherits the factory interface and registers the custom factory class with the buffer pool, making the framework more extensible, and caching the linked list to cache the already generated objects in the form of a linked list.

4. Summary
    • In fact, the principle of caching is the same, but the implementation of the same way, as long as we understand the principle, we can better read the source code.
    • Commons-pool provides two kinds of caching services Generickeyedobjectpool (k,v with key-value pairs), Genericobjectpool (T, only values), although there are some differences in functionality, but the implementation principle is the same.

Commons-pool Source Code Analysis Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.