Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

A service creates JAXBContext.newInstance(Invoice.class) inside a method called for each request. Under load CPU is high and heap shows many com.sun.xml.bind classes. What is wrong and how do you fix it?

Creating a JAXBContext is expensive: it reflects over the classes, builds a mapping model and may generate helper classes, so doing it on every request burns CPU and fills the heap with JAXB runtime classes. The fix is to create the context once, in a static final field or a Spring bean, and share it, since it is thread-safe, while creating Marshaller and Unmarshaller objects per use because they are cheap but not thread-safe.

Why this question is asked

This is a classic performance bug because the code looks harmless and works perfectly in tests. With one request per second nobody notices; at a few hundred requests per second the service spends most of its CPU building the same metadata again and again, and the garbage collector works hard to clean up after it. Interviewers like it because it tests whether we know which JAXB objects are heavy, which are thread-safe, and how to prove a fix with measurements. In this answer, we will look at the broken code, see what newInstance() really does, apply the fix, confirm it with a profiler, and see how Spring's Jaxb2Marshaller handles it for us.

1The Broken Code

Here is the pattern from the question. It is correct in behaviour, which is exactly why it reaches production.

Java
@Service
class InvoiceExporter {
String toXml(Invoice invoice) throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(Invoice.class); // runs on every request
Marshaller m = ctx.createMarshaller();
StringWriter w = new StringWriter();
m.marshal(invoice, w);
return w.toString();
}
}
// Load test, 200 requests/s: CPU 85%, p99 latency 140 ms
// Heap histogram: many org.glassfish.jaxb / com.sun.xml.bind runtime objects

The heap observation in the question is the clue. Class names starting with com.sun.xml.bind or org.glassfish.jaxb belong to the JAXB runtime, the implementation behind the API. Seeing many instances of them means the runtime is building its internal structures over and over.

2What JAXBContext.newInstance() Really Does

A JAXBContext is the runtime's complete understanding of how our classes map to XML. To build it, the runtime starts from Invoice and walks every class it can reach: the fields of Invoice, the classes of those fields, their superclasses, and any classes listed with @XmlSeeAlso. For each one it reads the annotations through reflection, works out element and attribute names, namespaces and types, and checks the whole model for errors. The reference implementation may also generate small accessor classes at runtime to read and write fields faster than reflection would.

All of that is work done once per context, and it is designed to be done once. The result is immutable and thread-safe, so the specification expects applications to create a context at startup and share it. When we build it per request, we pay the startup cost on every call, and we create a large graph of objects that becomes garbage immediately. Depending on the runtime, generated classes can also add pressure on metaspace, the area of memory where the JVM keeps class definitions.

Which JAXB objects are heavy and which are shared
ObjectCost to createThread-safe?How to hold it
JAXBContexthigh: reflection, model, generated codeyesonce, static final field or bean
Marshallerlownocreate per call, or ThreadLocal or pool
Unmarshallerlownocreate per call, or ThreadLocal or pool
Schema (validation)high: compiles the XSDyesonce, set on each unmarshaller

3The Fix: One Context, Fresh Marshallers

We move the context into a field that is created once. In a Spring application, the cleanest way is a bean, so the context is built at startup and injected where needed. A static final field works just as well in plain Java.

Java
@Configuration
class XmlConfig {
@Bean
JAXBContext invoiceContext() throws JAXBException {
return JAXBContext.newInstance(Invoice.class); // built once at startup
}
}
@Service
class InvoiceExporter {
private final JAXBContext ctx;
InvoiceExporter(JAXBContext ctx) { this.ctx = ctx; }
String toXml(Invoice invoice) throws JAXBException {
Marshaller m = ctx.createMarshaller(); // cheap, per call, never shared
StringWriter w = new StringWriter();
m.marshal(invoice, w);
return w.toString();
}
}
// Same load test, 200 requests/s: CPU 12%, p99 latency 9 ms

Notice that we still create a Marshaller on each call. That is fine: creating one from an existing context is cheap, little more than allocating a small object with default settings. What we must not do is share one Marshaller between threads, because it keeps per-operation state, and two requests writing through it at the same time can corrupt each other's output.

If profiling later shows that even marshaller creation matters, for example in a very high throughput path, we can keep one per thread in a ThreadLocal, or use a small pool. Both are rarely needed, and a ThreadLocal in a thread pool keeps its object for the life of the thread, so the simple per-call version is the right default. If a service needs several contexts, for example one per message type, a ConcurrentHashMap from class to context with computeIfAbsent() gives the same caching.

4Proving the Fix With Measurements

A fix like this should be confirmed, not assumed. Before changing code, we run a load test and record CPU use, latency percentiles and allocation rate, and capture a profile. A sampling profiler such as async-profiler, or a Java Flight Recorder recording opened in JDK Mission Control, will show JAXBContext.newInstance() and the runtime's model-building methods near the top of both the CPU and the allocation views.

After the fix we repeat the same test with the same load. The newInstance frames should disappear from the profile except once at startup, the allocation rate should drop sharply, and garbage collection pauses should become rarer. Recording these numbers in the ticket is worth the effort: it shows the fix worked and stops someone from reverting it later as an unnecessary change.

Properties
# Record 60 seconds of CPU and allocation on the running service (JDK Flight Recorder)
jcmd <pid> JFR.start duration=60s filename=before.jfr settings=profile
# ... run the load test, apply the fix, then record after.jfr the same way
# In JDK Mission Control: Method Profiling and Allocations views
# before: JAXBContext.newInstance and model building in the top frames
# after: only marshal() and our own code

5Letting Spring's Jaxb2Marshaller Handle It

Spring offers Jaxb2Marshaller in spring-oxm, which wraps JAXB behind Spring's Marshaller and Unmarshaller interfaces. We configure it as a bean with the classes or packages to bind, and it creates the JAXBContext once, lazily or at startup, and caches it. Each marshal call creates a fresh JAXB marshaller internally, so it is safe to share between threads. It is also what Spring Web Services and Spring Batch use, so using it keeps all XML configuration in one place.

Java
@Bean
Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller m = new Jaxb2Marshaller();
m.setClassesToBeBound(Invoice.class);
m.setMarshallerProperties(Map.of(jakarta.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true));
return m;
}
StringWriter w = new StringWriter();
jaxb2Marshaller.marshal(invoice, new StreamResult(w)); // context built once, reused

6Follow-up questions

Is it safe to create the context in a static initialiser?

Yes, and it is common. The only downside is error handling: newInstance() throws a checked JAXBException, so a static initialiser must wrap it, and a mapping error then appears as an ExceptionInInitializerError at first use. A Spring bean fails at startup with a clearer message, which many teams prefer.

Could the same problem happen with other libraries?

Yes. Jackson's ObjectMapper, schema compilation with SchemaFactory, XSLT Templates and regular expression Pattern objects all have an expensive, reusable, thread-safe part. Creating them per request causes the same symptoms, and the fix is the same: build once, share the thread-safe part.

Why did the heap show so many runtime classes instead of our own?

Because the cost is in JAXB's metadata, not in our objects. Each context holds information about every property of every bound class, so a few hundred contexts alive at the same time, waiting for garbage collection, outnumber the actual Invoice objects by far.

7Conclusion

In this answer, we saw that JAXBContext.newInstance() reflects over all reachable classes, builds and checks a mapping model and may generate code, so calling it per request wastes CPU and fills the heap with runtime metadata. The fix is one shared context in a static final field or a Spring bean, because it is thread-safe, with marshallers and unmarshallers created per use because they are cheap and not thread-safe. We confirm the fix with a profiler before and after, and Spring's Jaxb2Marshaller gives us the caching for free.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is that JAXBContext.newInstance runs on every request. Building a context is the expensive part of JAXB: the runtime walks every class reachable from Invoice, reads all the annotations by reflection, builds and validates a mapping model, and may generate accessor classes.

Then, if they want more

It is meant to happen once, and the context is thread-safe, so I would create it once, either in a static final field or, in Spring, as a bean, and inject it.

Marshaller and Unmarshaller are different: they are cheap to create but not thread-safe, so I create one per call from the shared context, and only consider a ThreadLocal or a pool if profiling shows that creation matters.

Before and after the change I would run the same load test and take a profile with JFR or async-profiler; before, newInstance and the model building dominate CPU and allocations, and after, they appear once at startup and the allocation rate drops sharply. I would put those numbers in the ticket.

And if the project uses Spring OXM, Jaxb2Marshaller already caches the context and creates a fresh JAXB marshaller per call, so I would just use that.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service creates JAXBContext.newInstance(Invoice.class) inside a method called for each...": https://scrivio-interview-library.netlify.app/java/jaxb/40363ad190/