The creation of a ``++JAXBContext.newInstance++`` is a costly operation, and should only be performed once per context and stored - preferably in a ``++static++`` member - for reuse. In fact, according to the JAXB 2.2 Specification: ____ To avoid the overhead involved in creating a JAXBContext instance, a JAXB application is encouraged to reuse a JAXBContext instance. An implementation of abstract class JAXBContext is required to be thread-safe, thus, multiple threads in an application can share the same JAXBContext instance. ____ This rule raises an issue when multiple instances are created for the same context path. == Noncompliant Code Example [source,java] ---- public void doSomething(List inputs) { for (String input : inputs) { Marshaller m = JAXBContext.newInstance(MyObj.class).createMarshaller(); // Noncompliant; context created in loop // ... } } public List getContexts(List inputs) { List result = new ArrayList<>(); for (Class input : inputs) { result.add(JAXBContext.newInstance(input); // Compliant; context path varies } return result; } public void doSomething2(List inputs) { Marshaller m = JAXBContext.newInstance(MyObj.class).createMarshaller(); // Noncompliant; context created each time method invoked for (String input : inputs) { // ... } } ---- == Compliant Solution [source,java] ---- private static JAXBContext context; static { try { context = JAXBContext.newInstance(MyObj.class); } catch (JAXBException e) { // handle exception... } } public void doSomething(List inputs) { Marshaller m = context.createMarshaller(); for (String input : inputs) { // ... } } public List getContexts(List inputs) { List result = new ArrayList<>(); for (Class input : inputs) { result.add(JAXBContext.newInstance(input); } return result; } ---- ifdef::env-github,rspecator-view[] ''' == Implementation Specification (visible only on this page) include::message.adoc[] ''' == Comments And Links (visible only on this page) include::comments-and-links.adoc[] endif::env-github,rspecator-view[]