1

Actually I want only one XStream instance. So I have below class:

public class XSteamTool{
    private static XStream xStream = new XStream();

    static{
        xStream.ignoreUnknownElements();
        xStream.registerConverter(new DateConverter(TimeZone.getDefault()));
    }

    public static String objToXml(Object obj){
        xStream.processAnnotations(obj.getClass());
        return xStream.toXML(obj);
    }

    public static <T> T xmlToObj(String xmlString, Class<T> clazz){
        xStream.processAnnotations(clazz);
        return(T)xStream.fromXML(xmlString);
    }
}

But this encounter issues in multi-thread environment. I find the note in official document:XStream is not thread-safe while it is configured. Unfortunately an annotation is defining a change in configuration that is now applied while object marshalling is processed
I try to synchronized before processAnnotations and that looks fine:

public static String objToXml(Object obj){
    synchronized (obj.getClass()) {
        xStream.processAnnotations(obj.getClass());             
    }
    return xStream.toXML(obj);
}

public static <T> T xmlToObj(String xmlString, Class<T> clazz){
    synchronized (clazz) {
        xStream.processAnnotations(clazz);              
    }
    return(T)xStream.fromXML(xmlString);
}

I wonder if the use is correct. Any suggestions are appreciated.

bluearrow
  • 856
  • 2
  • 11
  • 26

2 Answers2

2

At last we decide to share the xStream instance by Class (init the xStream only one time and reuse it in multi-thread environment):

private static Map<Class<?>, XStream> xStreamMap = Collections.synchronizedMap(new HashMap<Class<?>, XStream>());

private static XStream getXStreamInstance(Class<?> clazz) {
    if (xStreamMap.containsKey(clazz)) {
        return xStreamMap.get(clazz);
    }
    synchronized (clazz) {
        if (xStreamMap.containsKey(clazz)) {
            return xStreamMap.get(clazz);
        }
        XStream xStream = new XStream(new XppDriver(new NoNameCoder()));
        xStream.ignoreUnknownElements();
        xStream.registerConverter(new DateConverter(TimeZone.getDefault()));
        xStream.processAnnotations(clazz);
        xStreamMap.put(clazz, xStream);
        return xStream;
    }
}
bluearrow
  • 856
  • 2
  • 11
  • 26
0

What about a singleton implementation of xstream?

A quick example could be found here!

Community
  • 1
  • 1
Dirk Rother
  • 440
  • 1
  • 4
  • 18