Skip to content

[FEATURE]提供com.alibaba.fastjson2.JSONFactory.CacheItem缓存老化的策略配置,消减常驻内存占用 #3948

@gswcomputing

Description

@gswcomputing

问题描述:我们在使用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);
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions