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<>() ; 
 | 
     
 | 
    /** 
 | 
     * 生成对象 
 | 
     * 线程非安全的,所以用到synchronized 
 | 
     * @param clazz 预处理类 
 | 
     * @return 预处理类对象 
 | 
     */ 
 | 
    public static synchronized PrefixedDataAvailable getInstance(Class<?> clazz)throws Exception { 
 | 
        if(pool == null){ 
 | 
            pool = new HashMap<>() ; 
 | 
        } 
 | 
        String className = clazz.getName() ; 
 | 
        PrefixedDataAvailable obj = null ; 
 | 
         
 | 
        List<PrefixedDataAvailable> list = pool.get(className) ; 
 | 
        if(list == null){ 
 | 
            list = new ArrayList<>() ; 
 | 
            pool.put(className, list) ; 
 | 
        }else if(list.size() > 0){ 
 | 
            obj = list.get(0) ; 
 | 
            list.remove(0) ; 
 | 
        } 
 | 
         
 | 
        if(obj == null){ 
 | 
            try { 
 | 
                obj = (PrefixedDataAvailable)clazz.getDeclaredConstructor().newInstance() ; 
 | 
                //obj = (PrefixedDataAvailable)clazz.newInstance(); 
 | 
            } catch (Exception e) { 
 | 
                throw new Exception( "由" + className + "生成实例失败!"); 
 | 
            } 
 | 
        } 
 | 
        return obj ; 
 | 
    } 
 | 
     
 | 
    /** 
 | 
     * 把对象放回池中 
 | 
     * @param clazz 预处理类 
 | 
     * @param obj  预处理类对象 
 | 
     */ 
 | 
    public static void freeInstance(Class<?> clazz, PrefixedDataAvailable obj) { 
 | 
        if(pool != null){ 
 | 
            String className = clazz.getName() ; 
 | 
            List<PrefixedDataAvailable> list = pool.get(className) ; 
 | 
            if(list != null){ 
 | 
                list.add(obj) ; 
 | 
            } 
 | 
        } 
 | 
    }     
 | 
     
 | 
} 
 |