关键词:XStream单例;XStream性能问题

线上有一项目使用了XStream进行XML序列化、反序列化的方案,完成服务之间的接口报文Object与Xmlg格式之间的转化。

当线上业务量并不大的情况下,一切正常;但是发现当业务量突然加大的情况下,突然发现,线上服务器出现CPU居高不下,服务接口调用速度越来越慢,研究JVM日志分析,发现出现很多的RUNNABLE问题:

"http-nio-6680-exec-197" #4381 daemon prio=5 os_prio=0 tid=0x00007fda180aa000 nid=0x14e41b runnable [0x00007fd8d6536000]
   java.lang.Thread.State: RUNNABLE
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:348)
	at com.thoughtworks.xstream.XStream.registerConverterDynamically(XStream.java:929)
	at com.thoughtworks.xstream.XStream.setupConverters(XStream.java:917)
	at com.thoughtworks.xstream.XStream.<init>(XStream.java:574)
	at com.thoughtworks.xstream.XStream.<init>(XStream.java:496)
	at com.thoughtworks.xstream.XStream.<init>(XStream.java:465)
	at com.thoughtworks.xstream.XStream.<init>(XStream.java:411)
	at com.thoughtworks.xstream.XStream.<init>(XStream.java:378)
	at com.wings.frame.xml.XStreamInitializer.getInstance(XStreamInitializer.java:21)
	...

初步判断问题出在XStream上,分析XStream的源码,发现在XStream在new的时候会创建CompositeClassLoader(初始类加载器),并且不断new会不断创建,导致ygc需要扫描的内容越来越多,最终导致接口调用性能下降。

XStream是线程安全的,不需要重复初始化xstream对象,每一种类型实例化一个对象即可,而正是由于开发人员错误地在每次处理时都实例化一个新的xstream对象,才导致了该问题

XStream实例化的方法

		XStream xstream = XStreamInitializer.getInstance();
        xstream.processAnnotations(this.getClass());
        xstream.aliasSystemAttribute(null, "class");
        return xstream.toXML(this);

确定了问题,接下来就好办了,研究发现XStream支持单例模式,那就修改一下调用方法:

package com.wings.frame.tools;

import com.thoughtworks.xstream.XStream;
import java.io.*;
import java.util.concurrent.ConcurrentHashMap;

public class XmlHandler{

    private static final ConcurrentHashMap xStream = new ConcurrentHashMap<String, XStream>();
    
    /**
     * 初始化
     * @param objName
     * @return
     */
    private static XStream getXStream(Class<?> objName) {
        String key = objName.getName();
        if (xStream.get(key) == null)
            xStream.put(key, new XStream());
        return (XStream) xStream.get(key);
    }
    
    /**
     * 序列化
     * @param xmlHead
     * @param reqObjName
     * @return
     */
    public String toXML(String xmlHead,Class<?> reqObjName) {
        XStream xstream = getXStream(reqObjName);
        xstream.processAnnotations(reqObjName);
        //不显示class属性
        xstream.aliasSystemAttribute(null, "class");
        return xmlHead + xstream.toXML(reqObjName);
    }
    
    /**
     * 反序列化
     * @param clazz
     * @param xml
     * @param <T>
     * @return
     */
    public static <T> T parseXml(Class<T> clazz, String xml) {
        XStream xStream = getXStream(clazz);
        xStream.processAnnotations(clazz);
        @SuppressWarnings("unchecked")
        T t = (T) xStream.fromXML(xml);
        return t;
    }

}


不为明天而烦恼,不为昨天而叹息,只为今天更美好