common-pool

package com.open.sorce.common;

import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;

/**
* http://commons.apache.org/
* @author aircoder
*
*/
public class commonpool {
public static void main(String[] args) throws Exception {
GenericObjectPool pool = new GenericObjectPool(new TestCommonpool());
    pool.setMaxActive(5);//默认是8
           
           U u = (U) pool.borrowObject();//取出u
           U u0 = (U) pool.borrowObject();//取出u
           U u1 = (U) pool.borrowObject();//取出u
           U u2 = (U) pool.borrowObject();//取出u
           pool.returnObject(u1);//把取出的u还给对象池
           U u3 = (U) pool.borrowObject();//取出u
           pool.returnObject(u2);//把取出的u还给对象池
           U u4 = (U) pool.borrowObject();//取出u
           System.out.println("================:"+TestCommonpool.i);
            pool.returnObject(u);//把取出的u还给对象池
            System.out.println(TestCommonpool.i);// i <=4
}
}

class TestCommonpool implements PoolableObjectFactory{
public static  int i =0;
@Override
public void activateObject(Object arg0) throws Exception {
System.out.println("一个对象被激活");

}

@Override
public void destroyObject(Object arg0) throws Exception {
System.out.println("一个对象被销毁");

}

@Override
public Object makeObject() throws Exception {
System.out.println("一个对象被制作");

U u = new U();
u.setId(i);
u.setName(i*10);
i++;
return u;
}
/**
* 一个对象使用完后做清理工作
*/
@Override
public void passivateObject(Object arg0) throws Exception {
System.out.println("passivateObject");

}

@Override
public boolean validateObject(Object arg0) {
System.out.println("validateObject");
return false;
}

}

class U{
int id;
int name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
}

你可能感兴趣的:(java)