The question is a bit theoretical, what is the cost of creating JAXB context, marshaller and unmarshaller?
I\'ve found that my code could benefit from keeping the sa
I solved this problem using:
public class MyClassConstructor {
private final ThreadLocal<Unmarshaller> unmarshallerThreadLocal = new ThreadLocal<Unmarshaller>() {
protected synchronized Unmarshaller initialValue() {
try {
return jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw new IllegalStateException("Unable to create unmarshaller");
}
}
};
private final ThreadLocal<Marshaller> marshallerThreadLocal = new ThreadLocal<Marshaller>() {
protected synchronized Marshaller initialValue() {
try {
return jaxbContext.createMarshaller();
} catch (JAXBException e) {
throw new IllegalStateException("Unable to create marshaller");
}
}
};
private final JAXBContext jaxbContext;
private MyClassConstructor(){
try {
jaxbContext = JAXBContext.newInstance(Entity.class);
} catch (JAXBException e) {
throw new IllegalStateException("Unable to initialize");
}
}
}
Even better!! Based on the good solution from the post above, create the context just-once in the constructor, and save it instead of the class.
Replace the line:
private Class clazz;
with this one:
private JAXBContext jc;
And the main constructor with this one:
private Jaxb(Class clazz)
{
this.jc = JAXBContext.newInstance(clazz);
}
so in the getMarshaller/getUnmarshaller you can remove this line:
JAXBContext jc = JAXBContext.newInstance(clazz);
This improvement makes, in my case, that processing times drops from 60~70ms to just 5~10ms