Quick revision
The short answer
Instead of unmarshalling the whole document, we read it with a StAX XMLStreamReader, move to each <customer> start element, and call unmarshaller.unmarshal(reader, Customer.class) to turn just that element into an object. We process each object, write them to the database in batches, and let them go, so memory stays bounded by one element plus one batch. The XMLInputFactory must have DTDs and external entities disabled, and Spring Batch's StaxEventItemReader with a Jaxb2Marshaller does the same thing as a ready-made reader.
What to remember
In this answer, we saw why unmarshalling a 6 GB document fails: JAXB builds the entire object graph, which needs several times the file size in heap. The fix combines StAX and JAXB: a hardened XMLStreamReader skips to each <customer>, unmarshal(reader, Customer.class) maps just that element, and batches of objects are written and released, so memory stays bounded by one element plus one batch. We handled the off-by-one trap after unmarshal, flushing in JPA and restarts, and saw that Spring Batch's StaxEventItemReader with a Jaxb2Marshaller provides the same pattern ready-made.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Instead of unmarshalling the whole document, we read it with a StAX XMLStreamReader, move to each <customer> start element, and call unmarshaller.unmarshal(reader, Customer.class) to turn just that element into an object. We process each object, write them to the database in batches, and let them go, so memory stays bounded by one element plus one batch. The XMLInputFactory must have DTDs and external entities disabled, and Spring Batch's StaxEventItemReader with a Jaxb2Marshaller does the same thing as a ready-made reader.
Why this question is asked
Bulk XML files are still common: nightly customer exports, product catalogues, regulatory reports, data migrations. They grow over the years until one day the import that worked for a 200 MB file fails with OutOfMemoryError on 6 GB. Interviewers ask this because the fix shows whether we understand the difference between tree-based and streaming parsing, and whether we can combine them to keep JAXB's convenience without its memory cost. In this answer, we will see why the full unmarshal fails, recap StAX, write the streaming import, handle batching and security, and then look at the Spring Batch version.
1Why Unmarshalling the Whole File Fails
When we call unmarshaller.unmarshal(file) on the root of the document, JAXB builds the complete object graph before returning: a Customers object holding a list of 10 million Customer objects, each with its strings, dates and nested objects. A Java object takes far more memory than the XML text it came from, because of object headers, references and string overhead, so a 6 GB file can easily need 15 GB or more of heap. No reasonable heap setting fixes that, and even if it did, the next file would be bigger.
The deeper issue is that we do not need the whole graph. Each customer is imported on its own, so we only ever need one at a time. What we want is to read the file as a stream and materialise one customer, then the next.
2A Quick Recap of StAX
StAX, the Streaming API for XML in the javax.xml.stream package (still part of the JDK), reads a document as a sequence of events: start element, characters, end element and so on. Our code pulls the next event when it is ready, which is why it is called a pull parser. The parser keeps only a small buffer and the current position, so its memory use does not depend on the size of the file.
The useful part is that JAXB can unmarshal from an XMLStreamReader that is positioned on a start element. It reads exactly that element and its children, returns the object, and leaves the reader just after the element's end tag. So StAX skips through the file, and JAXB does the detailed mapping of each customer.
7 messages in order. Play them, or step through them one at a time.
Only one customer and one batch are in memory at any moment.
3Writing the Streaming Import
Here is the import loop. Notice the hardened XMLInputFactory: a file from a partner is untrusted input, so DTDs and external entities are disabled to prevent XXE, the XML external entity attack.
There is one subtle point in the loop. After unmarshal() returns, the reader is already positioned on the event after </customer>. If that event is the next <customer> start element, which happens when the file has no whitespace between elements, calling r.next() at that point would skip it and we would silently lose every second customer. That is why the loop only calls next() in the else branch and re-checks the current event after each unmarshal.
Using unmarshal(reader, Customer.class) instead of the plain unmarshal(reader) also means Customer does not need @XmlRootElement: we tell JAXB the type, and it returns a JAXBElement whose getValue() is our object. If the elements are in a namespace, we compare getNamespaceURI() as well as the local name.
4Batching, Memory and Restarting
Each batch of 1,000 customers is written with one batch insert, for example JDBC batch updates or a repository method that uses them, and then the list is cleared so those objects can be garbage collected. Memory is therefore bounded by one customer being read plus one batch waiting to be written, no matter whether the file holds a thousand customers or a hundred million. If we use JPA, we must also flush and clear the persistence context after each batch, otherwise the EntityManager keeps every saved entity in memory and we have just moved the leak.
A 10-million-element import takes a while, perhaps tens of minutes, so failures halfway through are realistic. We decide up front whether a failure rolls back everything or resumes. Committing per batch and recording the count of processed elements lets us restart from the last committed position, or we can import into a staging table and switch over at the end so readers never see half an import.
5The Spring Batch Version
Spring Batch packages this exact pattern. StaxEventItemReader reads the file with StAX, cuts it into fragments at each element with the configured name, and passes each fragment to a Spring OXM unmarshaller such as Jaxb2Marshaller. A chunk-oriented step then reads, processes and writes in chunks of a size we choose, commits after each chunk, and stores its position in the job repository so a failed job can restart where it stopped.
The builder methods shown follow Spring Batch 5; newer versions may change the step builder API, so check your version. Whichever we use, we still harden the XML input: check how the reader creates its XMLInputFactory in your version, and configure it to refuse DTDs if it does not already.
6Follow-up questions
Why not use SAX instead of StAX?
SAX also streams, but it pushes events into callbacks, so our code has to keep state between callbacks and cannot easily hand a subtree to JAXB. StAX lets us pull events in a simple loop and pass the reader to the unmarshaller at the right moment, which is why it combines so naturally with JAXB.
How would you parallelise the import?
Parsing a single XML stream is sequential, but the expensive part is usually the database. We can parse on one thread and hand batches to a small pool of writer threads through a bounded queue, which keeps memory bounded. Alternatively, split the file into several files first and import them in parallel, for example with a partitioned Spring Batch step.
What if one customer element is invalid?
Decide whether it should stop the import or be skipped and reported. With a schema set on the unmarshaller and a ValidationEventHandler, or with Spring Batch's skip policy, we can log the bad element with its position and continue, then report the skipped records at the end.
7Conclusion
In this answer, we saw why unmarshalling a 6 GB document fails: JAXB builds the entire object graph, which needs several times the file size in heap. The fix combines StAX and JAXB: a hardened XMLStreamReader skips to each <customer>, unmarshal(reader, Customer.class) maps just that element, and batches of objects are written and released, so memory stays bounded by one element plus one batch. We handled the off-by-one trap after unmarshal, flushing in JPA and restarts, and saw that Spring Batch's StaxEventItemReader with a Jaxb2Marshaller provides the same pattern ready-made.
Open with
Unmarshalling the root builds all 10 million Customer objects at once, and Java objects take several times the size of the XML, so no heap will be enough.
Then, if they want more
I would stream instead: create an XMLInputFactory with DTD support and external entities disabled, because the file is untrusted, and read it with an XMLStreamReader.
In the loop, when the reader is on a START_ELEMENT named customer, I call unmarshaller.unmarshal of the reader and Customer.class, which maps only that element and returns a JAXBElement, and leaves the reader after the end tag. I am careful not to call next again at that point, or I could skip an adjacent customer.
Each customer goes into a batch of, say, a thousand, which I write with a JDBC batch insert and then clear, so memory is bounded by one element plus one batch, around a hundred megabytes regardless of file size. If I use JPA, I flush and clear the persistence context per batch.
For restartability I would commit per batch and record progress. In a Spring application I would use Spring Batch: a StaxEventItemReader with fragment root element customer and a Jaxb2Marshaller, in a chunk step that commits every thousand items and can restart from where it failed.
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 "You must import a 6 GB XML file of 10 million <customer> elements with JAXB....": https://scrivio-interview-library.netlify.app/java/jaxb/686d942115/