package com.dy.common.mw.protocol; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class OnLinePool { protected static HashMap> pool = new HashMap<>() ; /** * 生成对象 * @param clazz 类型 * @return OnLine */ public static synchronized OnLine getInstance(Class clazz)throws Exception { if(pool == null){ pool = new HashMap<>() ; } String className = clazz.getName() ; OnLine obj = null ; List list = pool.get(className) ; if(list == null){ list = new ArrayList<>() ; }else{ obj = list.get(0) ; } if(obj != null){ list.remove(0) ; return obj ; }else{ try { obj = (OnLine)clazz.getDeclaredConstructor().newInstance() ; //obj = (OnLine)clazz.newInstance(); } catch (Exception e) { throw new Exception( "由" + className + "生成实例失败!"); } return obj ; } } /** * 把对象放回池中 * @param clazz 类 * @param obj 上线对象 */ public static void freeInstance(Class clazz, OnLine obj){ if(pool != null){ String className = clazz.getName() ; List list = pool.get(className) ; if(list != null){ list.add(obj) ; } } } }