[FEATURE]提供com.alibaba.fastjson2.JSONFactory.CacheItem缓存老化的策略配置,消减常驻内存占用
- Dominant language
- Java
- Stars
- 4.4k
- Forks
- 613
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 6
Description
问题描述:我们在使用com.alibaba.fastjson2做序列化时,服务发生oom,分析内存发现,com.alibaba.fastjson2.JSONFactory#CACHE_ITEMS[]有一个长度16的常驻内存占用37524k,其中CacheItem 中bytes属性长度262144,内存2.5m左右
static final CacheItem[] CACHE_ITEMS;
static {
final CacheItem[] items = new CacheItem[16];
for (int i = 0; i < items.length; i++) {
items[i] = new CacheItem();
}
CACHE_ITEMS = items;
}
static final class CacheItem {
volatile char[] chars;
volatile byte[] bytes;
}
希望提供一个配置:支持在此缓存读取完毕后将 CacheItem 中 chars 和 bytes 老化的策略 或 使用弱连接,这样gc可以回收
当前解决这个内存占用,使用反射将CacheItem bytes置为null,方案如下,是否合适:
try {
Field cacheItemsField = JSONFactory.class.getDeclaredField("CACHE_ITEMS");
cacheItemsField.setAccessible(true);
Object cacheItems = cacheItemsField.get(null);
if (cacheItems != null) {
int actualSize = java.lang.reflect.Array.getLength(cacheItems);
int cacheIndex = System.identityHashCode(Thread.currentThread()) & (actualSize - 1);
Object cacheItem = java.lang.reflect.Array.get(cacheItems, cacheIndex);
Class clazz = cacheItem.getClass();
Field field = getField(clazz, "bytes");
field.setAccessible(true);
field.set(cacheItem, null);
}
}
Contributor guide
Research direction
Start by reading com.alibaba.fastjson2.JSONFactory, especially the CACHE_ITEMS array and CacheItem chars and bytes fields, then trace how these buffers are read and retained. Compare an aging policy with weak references and define how configuration and garbage collection behavior should work; the issue is done when the selected strategy can reduce retained buffers without breaking serialization, with the relevant behavior verified.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- backend, performance
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100