java小菜鸟第一次写博客,有什么不对的地方,还望大神们指出,请勿喷~~~~~~,
接口访问时,程序可能会new 许多对象实例,比较耗资源,为节省这部分不必要的开支,写了一个小程序。
闲话不多说,上代码。如下:
对象池和线程池的管理类,值实例化一次。
1 /**
2 * 常量3 *4 *@authorGHD5 *6 */
7 public final classServerConstants {8
9 /**
10 * 线程池11 */
12 final static ExecutorService threadPool =Executors.newCachedThreadPool();13
14 /**
15 * SortRunnableManage对象池16 */
17 final static ObjectPool srmPool = new ObjectPool<>(SortRunnableManage.class);18
19 /**
20 * SortRunnable对象池21 */
22 final static ObjectPool srPool = new ObjectPool<>(SortRunnable.class);23 }
对象池管理类(泛型解决java向下转型问题)
1 /**
2 * 对象池3 *@authorGHD4 *5 */
6 public class ObjectPool{7
8 /**对象池*/
9 private GenericObjectPool pool = null;10
11 /**
12 * 构造函数,创建某一类型的对象池13 *@paramclz14 */
15 public ObjectPool(Classclz) {16 GenericObjectPoolConfig poolConfig = newGenericObjectPoolConfig();17 poolConfig.setMaxIdle(-1);//18 poolConfig.setMaxTotal(-1);19 poolConfig.setMinIdle(100);20 poolConfig.setLifo(false);21 pool = new GenericObjectPool(new ObjectFactory(clz), poolConfig);22 }23
24 /**
25 * 从对象池获取对象26 *@return
27 */
28 public T borrowObject() throwsException{29 return(T) pool.borrowObject();30 }31
32 /**
33 * 从对象池获取对象34 */
35 public void returnObject(T t) throwsException{36 pool.returnObject(t);37 }38
39 /**
40 * 关闭对象池41 */
42 public void close() throwsException{43 pool.close();44 }45
46 /**
47 * 清空对象池48 */
49 public void clear() throwsException{50 pool.clear();51 }52 }53
54 /**
55 * 对象工厂56 */
57 class ObjectFactory extends BasePooledObjectFactory{58
59 private Classclz;60
61 public ObjectFactory(Classclz) {62 this.clz =clz;63 }64
65 @Override66 public T create() throwsException {67 return this.clz.newInstance();68 }69
70 @Override71 public PooledObjectwrap(T t) {72 return new DefaultPooledObject(t);73 }74 }
线程管理类
public class SortRunnableManage{
/** 运行中的线程 */
List runningRunnables = new ArrayList();
/** 响应用户的结果集*/
List result = new ArrayList();
/**
* 获取处理线程
* @param runnable
* @throws Exception
*/
public SortRunnable getSortRunnable() throws Exception {
SortRunnable sortRunnable = ServerConstants.srPool.borrowObject();
runningRunnables.add(sortRunnable);
return sortRunnable;
}
/**
* 获取结果集合
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List getResult() throws Exception {
// 清空上一个客户留下来的结果集
result.clear();
while(runningRunnables.size() > 0){
Iterator itor = runningRunnables.iterator();
while(itor.hasNext()){
SortRunnable testRunable = (SortRunnable) itor.next();
if(testRunable.isClosed()){
result.add(testRunable.getResult());
itor.remove();
ServerConstants.srPool.returnObject(testRunable);
}
try {Thread.sleep(3);} catch (Exception e) {e.printStackTrace();}
}
}
return (List) result;
}
}
单个线程类(反射)
1 public class SortRunnable implementsRunnable{2 //返回结果
3 privateObject result;4 //线程状态
5 private booleanclosed;6 //注入要执行的方法类实例
7 privateMethod method;8 //注入要执行的方法类实例
9 privateObject instance;10 //注入要执行的方法参数
11 privateObject[] params;12
13
14 @Override15 public voidrun() {16 closed = false;17 try{18 result =method.invoke(instance, params);19 } catch(Exception e) {20 //TODO Auto-generated catch block
21 e.printStackTrace();22 }23 closed = true;24 }25
26 public booleanisClosed() {27 returnclosed;28 }29 publicObject getResult() {30 returnresult;31 }
//方法和参数赋值32 public void setMethodAndParams(String methodName, Object instance, Object...params) throwsNoSuchMethodException, SecurityException {33 for(Method mod : instance.getClass().getDeclaredMethods()){34 if(mod.getName().equals(methodName)){35 this.method =mod;36 break;37 }38 }39 this.instance =instance;40 this.params =params;41 }42
43 }
对象
1 public classTestData {2 private intnum;3 privateString user;4
5 publicTestData(){}6
7 public TestData(intnum, String user) {8 this.num =num;9 this.user =user;10 }11
12 public intgetNum() {13 returnnum;14 }15
16 public void setNum(intnum) {17 this.num =num;18 }19
20 publicString getUser() {21 returnuser;22 }23
24 public voidsetUser(String user) {25 this.user =user;26 }27 }
测试
1 public static void main(String[] args) throwsException {2 Test t = newTest();3 t.multiUserSingleData();4 }5
6 void multiUserSingleData() throwsException{7 for(int i = 0 ;i < 10; i++){8 singleUserSingleData();9 }10 }11
12 void singleUserSingleData() throwsException{13 int a = 1;14 String b = "2";15 TestData testData = newTestData() ;16 SortRunnableManage sortRunnableManage =ServerConstants.srmPool.borrowObject();17 SortRunnable sortRunnable =sortRunnableManage.getSortRunnable();18 ServerConstants.threadPool.execute(sortRunnable);19 sortRunnable.setMethodAndParams("runInvoke", this, newObject[]{a, b , testData});20
21 List list =sortRunnableManage.getResult();22 System.out.println(sortRunnableManage.toString());23 System.out.println(sortRunnable.toString());24 }
以上为5个客户同时一次访问,结果如下:
sortRunnable一直使用的是同一个对象 证明sortRunnable的对象池的起作用了
上述代码,cope直接就能运行
继续测试 5个客户同时5次访问,同样没问题,代码就给,自己写吧。