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.

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

What about a singleton implementation of xstream?

A quick example could be found here!

1 Comment

Thanks. But it's not only about singleton.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.