Quick revision
The short answer
We stream it with Gson's JsonReader: call beginArray(), then while hasNext() read one transaction at a time with gson.fromJson(reader, Transaction.class), and finish with endArray(). Only one element is in memory at a time, so the heap stays flat no matter how big the file is. We wrap the input in a buffered reader with explicit UTF-8, hand items downstream in batches such as 1,000 database inserts, and watch for MalformedJsonException and JsonSyntaxException, deciding whether to skip or abort and recording the position so the job can restart.
What to remember
In this answer, we saw that loading a 3 GB array as a String, list or tree exhausts a 512 MB heap, while JsonReader with beginArray, hasNext, a per-element gson.fromJson(reader, Transaction.class) and endArray keeps only one element in memory. We opened the file as buffered, explicit UTF-8, inserted in batches of 1,000, logged positions from getPath(), skipped only elements that failed validation while aborting on syntax errors, and restarted from a saved checkpoint with skipValue.
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.
We stream it with Gson's JsonReader: call beginArray(), then while hasNext() read one transaction at a time with gson.fromJson(reader, Transaction.class), and finish with endArray(). Only one element is in memory at a time, so the heap stays flat no matter how big the file is. We wrap the input in a buffered reader with explicit UTF-8, hand items downstream in batches such as 1,000 database inserts, and watch for MalformedJsonException and JsonSyntaxException, deciding whether to skip or abort and recording the position so the job can restart.
Why this question is asked
A 3 GB file will not fit in a 512 MB heap, and with object overhead its parsed form would need several times its size even in a big heap. Partner exports, bank statements and event dumps routinely reach that size, so a backend engineer needs a way to process them in constant memory. Interviewers ask this scenario because it separates people who only know fromJson(String) from people who understand streaming, and because the error handling is where real jobs fail. In this answer, we will see why the usual approaches fail, write the streaming loop, set up the input correctly, process in batches, and handle malformed data and restarts.
1Why the Usual Approaches Run Out of Memory
gson.fromJson(text, listType) needs the whole file as a String first, which alone is about 3 GB of characters and more in memory, then a List holding every Transaction at once. JsonParser.parseReader builds a JsonElement tree of the entire document, again with all of it in memory, plus the overhead of one object per value. Both approaches keep everything alive at the same moment, so both end in OutOfMemoryError long before the end of the file.
What we need instead is to hold just one transaction at a time: read it, process it, let it be garbage collected, and move on. That is what a streaming parser gives us.
2The Streaming Loop
JsonReader reads JSON as a sequence of tokens: begin array, begin object, name, value, end object, and so on. We drive it ourselves for the outer array and let Gson bind each element to a class.
- Open the file as buffered UTF-864 KB buffer
- beginArray()consume [
- hasNext()?YesRead one Transaction with fromJsonNoendArray(), flush the last batch
- Batch full (1,000)?YesInsert batch, save checkpointNoLoop to hasNext()
4 steps in order. Play them, or step through them one at a time.
Notice that gson.fromJson(reader, type) consumes exactly one value, the next object, and leaves the reader positioned at the following element. That is what lets us mix manual token handling with normal data binding. Each Transaction becomes garbage as soon as its batch is written, so memory stays flat.
3Setting Up the Input Correctly
Two details in the opening lines matter. First, the charset. JSON exchanged between systems must be UTF-8, and new InputStreamReader(stream) without a charset uses the platform default. Since Java 18 the default is UTF-8 on every platform, but being explicit protects us on older runtimes and makes the intent clear. A wrong charset does not fail; it silently corrupts names with accented letters.
Second, buffering. Reading a 3 GB file one small read at a time is slow, so we wrap it in a BufferedReader; JsonReader has some buffering of its own, but an explicit buffer of tens of kilobytes keeps the number of system calls low. With try-with-resources, closing the JsonReader closes the whole chain down to the file.
4Batching Downstream
Streaming solves memory, but inserting three million rows one by one would take hours, with a database round trip per row. So we collect items into batches of about 1,000 and write each batch with one JDBC batch insert, or one saveAll with batching enabled in Hibernate, in its own transaction. A batch of 1,000 small objects is a few hundred kilobytes, so it fits easily in the heap, and the database does far less work per row.
The batch size is a trade-off: bigger batches mean fewer round trips but more memory and longer transactions, and more work to redo after a failure. Values between 500 and 5,000 are typical; we measure with the real database.
5Errors to Watch For and Restarting
Several things can go wrong. If the file is not valid JSON, for example truncated by a broken transfer or containing an unescaped quote, JsonReader throws MalformedJsonException, a subclass of IOException; when the error happens inside gson.fromJson, Gson wraps it in JsonSyntaxException. If the JSON is valid but a value has the wrong type, such as a string where a number belongs, we get JsonSyntaxException too. Messages include the line, column and a path such as $[48213].amount, and reader.getPath() gives the path at any moment, which is what we log.
Whether to skip or abort depends on the kind of error. A structurally valid element that fails our own validation, such as a negative amount, can be skipped safely: we record it in an error table with its index and continue. A syntax error is different: the reader no longer knows where the next element starts, so continuing is unreliable. We abort, mark the job failed, and report the position.
The checkpoint makes restarts cheap. Because we saved the index of the last committed batch, a restarted job opens the file, calls beginArray(), and skips that many elements with reader.skipValue(), which moves past an element without building any objects, then continues normally. Combined with idempotent inserts, for example on the transaction id, a crash in the middle of a batch cannot create duplicates.
6Follow-up questions
Would increasing the heap be a reasonable fix?
Not for this. The memory needed by fromJson on the whole file grows with the file, so a bigger heap only moves the limit, and next month's 6 GB file fails again. Streaming makes memory independent of file size.
How would the same job look with Jackson?
Jackson's JsonParser plays the role of JsonReader: we call nextToken() to enter the array, then mapper.readValue(parser, Transaction.class) for each element, or use mapper.readerFor(Transaction.class).readValues(input), which returns a MappingIterator over the elements. The structure of the loop is the same.
Could we process elements in parallel?
Parsing one JSON array is sequential, but the downstream work does not have to be. We can hand batches to a small pool of workers through a bounded queue, which keeps memory bounded. If the partner can send newline-delimited JSON instead, the file can even be split and parsed in parallel.
7Conclusion
In this answer, we saw that loading a 3 GB array as a String, list or tree exhausts a 512 MB heap, while JsonReader with beginArray, hasNext, a per-element gson.fromJson(reader, Transaction.class) and endArray keeps only one element in memory. We opened the file as buffered, explicit UTF-8, inserted in batches of 1,000, logged positions from getPath(), skipped only elements that failed validation while aborting on syntax errors, and restarted from a saved checkpoint with skipValue.
Open with
I would never load the whole thing. Reading it as a String or a JsonElement tree keeps the entire document in memory, which cannot work in 512 MB.
Then, if they want more
Instead I open the file as a BufferedReader over an InputStreamReader with explicit UTF-8, wrap it in a Gson JsonReader, call beginArray, and then loop while hasNext, reading one element at a time with gson.fromJson(reader, Transaction.class), which consumes exactly one object. At the end I call endArray.
Only the current element and the current batch are in memory, so heap use stays flat regardless of file size. Downstream, I collect items into batches of about 1,000 and write each with a JDBC batch insert in its own transaction, saving a checkpoint with the index of the last committed element.
For errors, I watch for MalformedJsonException from the reader and JsonSyntaxException from Gson, and I log reader.getPath and the line and column. If an element is valid JSON but fails validation, I record it in an error table and continue. If it is a syntax error, I abort, because the reader cannot reliably find the next element.
On restart I skip the already processed elements with skipValue, and idempotent inserts on the transaction id prevent duplicates.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 18
- 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 process a 3 GB JSON array of transactions in a service with a 512 MB heap. How...": https://scrivio-interview-library.netlify.app/java/json-libraries/35d4685fdb/