JAXB creating context and marshallers cost
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
JAXBContext
is thread safe and should only be created once and reused to avoid the cost of initializing the metadata multiple times. Marshaller
and Unmarshaller
are not thread safe, but are lightweight to create and could be created per operation.
Ideally, you should have a singleton JAXBContext
and local instances of Marshaller
and Unmarshaller
.
JAXBContext
instances are thread-safe while Marshaller
and Unmarshaller
instances are not thread-safe and should never be shared across threads.
It's a pity that this isn't specifically described in the javadoc. What I can tell is that Spring uses a global JAXBContext, shared between threads, whereas it creates a new marshaller for each marshalling operation, with a javadoc comment in the code saying that JAXB marshallers are not necessarily thread-safe.
The same is said on this page:https://javaee.github.io/jaxb-v2/doc/user-guide/ch03.html#other-miscellaneous-topics-performance-and-thread-safety.
I would guess that creating a JAXBContext is a costly operation, because it involves scanning classes and packages for annotations. But measuring it is the best way to know.