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

----
public void doSomething(List<MyObj> inputs) {
  for (String input : inputs) {
    Marshaller m = JAXBContext.newInstance(MyObj.class).createMarshaller();  // Noncompliant; context created in loop
    // ... 
  }
}

public List<JAXBContext> getContexts(List<Class> inputs) {
  List<JAXBContext> result = new ArrayList<>();
  for (Class input : inputs) {
    result.add(JAXBContext.newInstance(input);  // Compliant; context path varies
  }
  return result;
}

public void doSomething2(List<MyObj> inputs) {
  Marshaller m = JAXBContext.newInstance(MyObj.class).createMarshaller();  // Noncompliant; context created each time method invoked
  for (String input : inputs) {
    // ...
  }
}
----


== Compliant Solution

----

private static JAXBContext context;
static {
  try {
    context = JAXBContext.newInstance(MyObj.class);
  } catch (JAXBException e) {
    // handle exception...
  }
}

public void doSomething(List<MyObj> inputs) {
  Marshaller m = context.createMarshaller();
  for (String input : inputs) {
    // ... 
  }
}

public List<JAXBContext> getContexts(List<Class> inputs) {
  List<JAXBContext> result = new ArrayList<>();
  for (Class input : inputs) {
    result.add(JAXBContext.newInstance(input);
  }
  return result;
}
----


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
