我想在多线程环境中处理XML字符串的实例。 但在官方文档中:XStream在配置时不是线程安全的。不幸的是,注释正在定义在处理对象编组时现在应用的配置更改。 所以我想通过Class共享xStream实例。安全吗? 我想知道使用是否正确。任何建议都表示赞赏。
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.processAnnotations(clazz);
xStreamMap.put(clazz, xStream);
return xStream;
}
}
public static Object fromXML(String xml, final Class type) throws AppExceptionEx {
try {
return getXStreamInstance(type).fromXML(xml);
} catch (XStreamException e) {
throw new AppExceptionEx(ErrorNum.XML_ERROR,e.getMessage());
}
}
public static String toXml(Object obj) throws AppExceptionEx {
try {
return getXStreamInstance(obj.getClass()).toXML(obj);
} catch (XStreamException e) {
throw new AppExceptionEx(ErrorNum.MAKE_XML_ERROR,
ErrorNum.MAKE_XML_ERROR_MSG);
}
}