Quick revision
The short answer
DOM builds the whole document as a tree of objects before we can read any of it, and each element, attribute and text node costs an object with several references plus its strings, so the tree is often 5 to 10 times the file size: an 800 MB file can need 4 to 8 GB. I would switch to streaming with StAX, reading one record at a time and optionally binding each record to an object, so memory stays flat no matter how big the file is.
What to remember
In this answer, we saw that DOM holds the whole file as a tree of node objects, each with references and strings, so memory is often 5 to 10 times the file size and an 800 MB file cannot fit in a 4 GB heap. A bigger heap only moves the limit and makes garbage collection heavier. Streaming with StAX keeps memory proportional to one record, and a hybrid that streams with StAX and binds each record with Jakarta XML Binding keeps the code pleasant. We also turned off DTD processing to block entity expansion, and tested the job with a small heap and a large synthetic file.
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.
DOM builds the whole document as a tree of objects before we can read any of it, and each element, attribute and text node costs an object with several references plus its strings, so the tree is often 5 to 10 times the file size: an 800 MB file can need 4 to 8 GB. I would switch to streaming with StAX, reading one record at a time and optionally binding each record to an object, so memory stays flat no matter how big the file is.
Why this question is asked
Batch jobs that read XML usually start with small files and DOM, because DOM is the easiest API to learn. Years later the files have grown, and one night the job dies with OutOfMemoryError. Interviewers ask this scenario to see whether we can reason about where memory goes, and whether we reach for a design change rather than a bigger heap. In this answer, we will estimate the memory cost of a DOM tree, see why raising the heap is not a real fix, rewrite the job to stream with StAX, look at a hybrid that keeps the convenience of objects per record, check the entity expansion trap, and finally see how to test memory behaviour.
1A Quick Recap of How DOM Loads a File
With DOM, DocumentBuilder.parse() reads the entire file and returns a Document only when the last byte has been processed. Every element becomes an Element object, every attribute an Attr object, and every piece of text, including the whitespace between tags, a Text object. Each node keeps references to its parent, its siblings and its children, plus its name and value as Java strings.
Our code can only start working after the whole tree exists. So the peak memory of the job is the full tree plus whatever our code builds from it, and it grows in direct proportion to the input size.
2Estimating the Memory Cost
Let us do the arithmetic for a typical record-oriented file. Suppose each record looks like <txn id="9"><amount>12.50</amount><currency>EUR</currency></txn> with indentation, about 100 bytes on disk. That small record becomes about ten nodes: the txn element, its id attribute, two child elements, two text values and around four whitespace text nodes.
Each node object has a header, several reference fields and often its own String objects for name and value. Even with compressed references and the compact strings Java has used since Java 9, a node with its strings easily costs 50 to 100 bytes. Ten nodes per 100-byte record means 500 to 1,000 bytes in memory for every 100 bytes on disk, which is the 5 to 10 times factor. For an 800 MB file that is 4 to 8 GB, so a 4 GB heap cannot hold it, and the exact factor depends on the parser and the shape of the data.
| Part of the tree | Nodes | Rough cost |
|---|---|---|
| txn element and its id attribute | 2 | about 150 bytes |
| amount and currency elements | 2 | about 150 bytes |
| their text values | 2 | about 120 bytes |
| whitespace text between tags | about 4 | about 250 bytes |
| total per record | about 10 | 500 to 1,000 bytes, 5 to 10 times the file |
3Why a Bigger Heap Is Not the Answer
Raising -Xmx to 12 GB might make tonight's run pass. But the files keep growing, so we have only moved the limit, and we now need machines with much more memory for a job that only ever looks at one record at a time. A huge heap full of long-lived objects also makes garbage collection work harder: the collector has to trace millions of live nodes, and pauses or CPU overhead grow with them.
There is a second cost: time to first work. With DOM, nothing useful happens until the whole 800 MB has been parsed. With streaming, the first record is processed after a few microseconds. So the real fix is to change how we read the file, so that memory depends on the size of one record, not the size of the file.
4Streaming the File With StAX
StAX, the Streaming API for XML in javax.xml.stream, lets us pull events from the parser one at a time with XMLStreamReader. We keep only the fields of the current record in local variables and hand each finished record to the next step.
Notice that nothing refers to a record after it has been written, so the garbage collector can reclaim it almost immediately. The heap now holds the parser's small buffer and one record, whether the file is 8 MB or 80 GB. In practice such a job runs comfortably in a few hundred megabytes.
5A Hybrid: Stream the File, Bind One Record at a Time
Hand-written field extraction gets tedious when a record has 40 fields and nested parts. A good middle ground is to stream with StAX to each record's start tag, and then let Jakarta XML Binding (the jakarta.xml.bind API, formerly JAXB) unmarshal just that element into an annotated class. The unmarshaller reads from the same XMLStreamReader and leaves the cursor on the event just after the record's end tag, which is why the loop below only calls next() when it did not unmarshal; otherwise, in a file without whitespace between records, we would skip the next record's start tag.
- Open XMLStreamReader on the fileDTD support off
- Next eventcursor moves forward
- Start of a <txn> element?YesBind this one elementNoSkip the event
- Unmarshal one TxnJakarta XML Binding reads up to </txn>
- Write the recordobject becomes garbage right away
- More events?YesBack to next eventNoClose reader and stream
6 steps in order. Play them, or step through them one at a time.
Memory is bounded by one record plus the parser buffer.
The same idea works with a small DOM per record (a Transformer with a StAXSource for the subtree) when the rest of the code base already speaks DOM. Either way we get convenient objects without ever holding more than one record.
6Check for Entity Expansion Too
Not every OutOfMemoryError comes from file size. If DTD processing is enabled, a tiny document can declare entities that refer to other entities, so that a few kilobytes expand to gigabytes of text when the parser replaces them; this is the billion laughs attack. The JDK has built-in limits on entity expansion when secure processing is active, but the exact defaults have changed between releases, so check your version and do not rely on them.
For batch files from partners, the simplest protection is to refuse DTDs entirely: SUPPORT_DTD set to false for StAX, or the disallow-doctype-decl feature for DOM and SAX parsers. Then entity tricks fail fast with a clear error instead of eating the heap.
7Follow-up questions
How would you test memory behaviour with large files?
I would generate a synthetic file of realistic shape, for example 2 GB of records, in a test setup step rather than committing it, and run the job with a deliberately small heap such as -Xmx256m. If it streams correctly it passes; if it accumulates anything per record, it fails quickly with OutOfMemoryError. During a longer run I would record with Java Flight Recorder or watch the heap with jcmd GC.heap_info, and check that used heap after each collection stays flat rather than climbing. A heap histogram (jmap -histo or jcmd GC.class_histogram) shows which classes grow if it does climb.
Is SAX just as good as StAX here?
For memory, yes: both are streaming parsers and keep only a small buffer. StAX is usually easier because our code pulls events and keeps state in local variables, and it combines naturally with Jakarta XML Binding for the per-record hybrid. SAX is fine if the team already has SAX handlers.
Can we keep DOM if we split the file first?
Splitting a huge file into smaller ones is a reasonable stopgap when DOM code is complex and well tested, but splitting correctly also needs a streaming parser, and it adds a step and temporary storage. Streaming the records directly is usually less work in total.
8Conclusion
In this answer, we saw that DOM holds the whole file as a tree of node objects, each with references and strings, so memory is often 5 to 10 times the file size and an 800 MB file cannot fit in a 4 GB heap. A bigger heap only moves the limit and makes garbage collection heavier. Streaming with StAX keeps memory proportional to one record, and a hybrid that streams with StAX and binds each record with Jakarta XML Binding keeps the code pleasant. We also turned off DTD processing to block entity expansion, and tested the job with a small heap and a large synthetic file.
Open with
The problem is that DOM materialises the whole file before I can touch any of it. Every element, attribute and text node, including the whitespace between tags, is a Java object with parent, child and sibling references and its own strings.
Then, if they want more
In practice that is five to ten times the file size, so 800 MB of XML needs something like four to eight gigabytes, and a 4 GB heap simply cannot hold it. I would not just raise the heap: the files will keep growing, we pay for a huge heap on every run, and garbage collection gets heavier.
Instead I would switch to StAX with an XMLStreamReader, pull events, collect the fields of one record in local variables, and hand each record on as soon as I reach its end tag.
If records are large or nested, I would stream to each record's start tag and let Jakarta XML Binding unmarshal just that element from the reader, so I still get objects but only one at a time. I would also disable DTD support, because entity expansion can blow up memory from tiny inputs.
To prove the fix, I would run the job against a generated multi-gigabyte file with a small heap like 256 MB and watch the heap after collections stay flat.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- 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 batch job loads 800 MB XML files with DOM and fails with OutOfMemoryError on a 4 GB...": https://scrivio-interview-library.netlify.app/java/xml-processing/25d91dd8cd/