Article / 2026/05/31
内存溢出
bundle
内存溢出的一些处理
字节数据的对象池的复用
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
public class LruByteArrayPool {
private static final float LOAD_FACTOR = 0.75f;
private final LinkedHashMap<Integer, LinkedList<byte[]>> pool;
private final int maxCapacity; // 池中最大字节数组数
private int index = 0;
private final String tag;
public LruByteArrayPool(int maxCapacity, String tag) {
this.tag = tag;
this.maxCapacity = maxCapacity;
this.pool = new LinkedHashMap<>(16, LOAD_FACTOR, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, LinkedList<byte[]>> eldest) {
return size() > LruByteArrayPool.this.maxCapacity; // 当超出最大容量时,移除最老的条目
}
};
}
public synchronized byte[] getByteArray(int length) {
LinkedList<byte[]> list = pool.get(length);
if (list != null && !list.isEmpty()) {
return list.removeFirst(); // 重用现有数组
}
index++;
return new byte[length]; // 池中无可用数组,创建新数组
}
public synchronized void returnByteArray(byte[] array) {
if (array == null) {
return;
}
Arrays.fill(array, (byte) 0);
pool.computeIfAbsent(array.length, k -> new LinkedList<>()).addFirst(array);
// 维护池大小在LRU逻辑中自动处理
}
}
对象池的复用
- bundle
Giscus 未启用:请在
src/site.config.ts中配置 repoId 与 categoryId。