问题
I have implemented a util class with the following static method:
public static String objToXml(JAXBContext jaxbContext, ClassA obj) throws Exception{
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
}
My understanding is that JAXB Marshaller and StringWriter are both thread safe ... but I want to double confirm if I implement a static method like this.. and have multiple threads calling objToXml method concurrently, would there be any potential issue?
回答1:
Yes you must create a new Marshaller each time around if you are planning to use them multi-threaded.
See Unofficial JAXB Guide
The JAXBContext class is thread safe, but the Marshaller, Unmarshaller, and Validator classes are not thread safe.
来源:https://stackoverflow.com/questions/36062415/create-new-jaxb-marshaller-instance-in-static-method-is-it-threadsafe