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