fastjson中JSON.toJSONString内存泄露如何解决

   日期:2020-10-19     浏览:634    评论:0    
核心提示:内存泄露将数据写入到了Tomcat线程池管理的线程中产生原因public static String toJSONString(Object object, // SerializeConfig config, // SerializeFilter[] filters, //

内存泄露

将数据写入到了Tomcat线程池管理的线程中

产生原因

public static String toJSONString(Object object, // 
                                      SerializeConfig config, // 
                                      SerializeFilter[] filters, // 
                                      String dateFormat, //
                                      int defaultFeatures, // 
                                      SerializerFeature... features) {
        SerializeWriter out = new SerializeWriter(null, defaultFeatures, features);

        try {
            JSONSerializer serializer = new JSONSerializer(out, config);
            
            if (dateFormat != null && dateFormat.length() != 0) {
                serializer.setDateFormat(dateFormat);
                serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
            }

            if (filters != null) {
                for (SerializeFilter filter : filters) {
                    serializer.addFilter(filter);
                }
            }

            serializer.write(object);

            return out.toString();
        } finally {
            //泄露的地方
            //将buf中的json字符串放入到threadLocal
            out.close();
        }
    }

进入这个方法,仔细看一下

public void close() {
        if (writer != null && count > 0) {
            flush();
        }
        //解决方案就从这个地方下手
        if (buf.length <= BUFFER_THRESHOLD) {
            bufLocal.set(buf);
        }

        this.buf = null;
    }

解决方案

A

不再使用fastjson

B

调整BUFFER_THRESHOLD参数

如何调整

public static void main(String[] args) {
        //在启动类上加入该参数,进行修改
        System.setProperty("fastjson.serializer_buffer_threshold","64");
        SpringApplication.run(SpringbootDemoApplication.class, args);


    }

为什么这样调整会起作用

这个值不可以设置的小于64,也不可以大于1024*64,否则都不会起作用

 而我们的目的是控制BUFFER_THRESHOLD,进行影响buf,为的就是不让buf写入threadLocal,或者尽可能少的写入threadLocal

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服