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
Creating JAXBContext within a enum and accessing it within application Thread to create Marshaller/Unmarshaller will suffice.
public enum MyApplicationJAXBContext {
REQ(Request.class), RESP(Response.class);
private final JAXBContext jaxbContext;
MyApplicationJAXBContext(Class contextClass) {
try {
jaxbContext = JAXBContext.newInstance(contextClass);
} catch (JAXBException e)
throw new RunTimeException(e);
// Lets caller decide what to do ?
}
}
public JAXBContext getJaxbContext() {
return jaxbContext;
}
}
public class MyAppCallable implements Callable {
private final Request req;
public MyAppCallable(Request req) {
this.req = req;
}
public Response call() {
Marshaller marshaller = MyApplicationJAXBContext.REQ.getJaxbContext().createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Anything else you want to configure properties
Unmarshaller unmarshaller = MyApplicationJAXBContext.RESP.getJaxbContext().createUnmarshaller();
/**
All other logic you want to do after req/rsp usage and return Response
**/
}
}