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.