wuzeyu
2024-05-15 fbd4cf5aeb4274938c12030e5d235c65c20c19c3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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<>() ;
        }else{
            obj = list.get(0) ;
        }
        
        if(obj != null){
            list.remove(0) ;
            return obj ;
        }else{
            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) ;
            }
        }
    }    
    
}