111
hxb
2022-11-24 0a3e07f10937484145f33c7560607b4b2353cb81
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
package com.mm.android.deviceaddmodule.mobilecommon.eventbus.event;
 
import java.util.ArrayList;
import java.util.List;
 
 
public class DefaultCachePool<T> implements ICachePool<T>{
    
    private static final int DEFAULT_MAX_POOL_SIZE = 1000;
    
    private final List<T> cachePool;
    
    private int maxPoolSize = DEFAULT_MAX_POOL_SIZE;
    
    private Class<T> cls;
    
    public DefaultCachePool(Class<T> cls, int maxPoolSize)
    {
        cachePool = new ArrayList<>();
        this.maxPoolSize = maxPoolSize;
        this.cls = cls;
    }
 
    @Override
    public T obtain()
    {
        synchronized (cachePool) {
            int size = cachePool.size();
            if (size > 0) {
                return cachePool.remove(size - 1);
            }
        }
        
        T obj = null;
        
        try {
            obj = cls.newInstance();
        } catch (Exception e) {
            obj = null;
        } 
        
        return obj;
    }
 
    @Override
    public void recycle(T o)
    {
         synchronized (cachePool) {
                if (cachePool.size() < maxPoolSize) {
                    cachePool.add(o);
                }
         }
    }
}