streaming-huge-json: 1 GiB streaming vs tree vs binding benchmark (Jackson 3.2.4, JDK 25) for the rewritten streaming post

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CifR2BE7PBvRy5hT8TS9oz
This commit is contained in:
Claude
2026-10-26 02:03:57 +00:00
parent b1663c235d
commit 1d0cd8b36e
17 changed files with 560 additions and 0 deletions
@@ -0,0 +1,85 @@
package com.ankurm.jackson3.streaminghuge;
import tools.jackson.core.ObjectWriteContext;
import tools.jackson.core.json.JsonFactory;
import tools.jackson.core.JsonGenerator;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.SplittableRandom;
/**
* Writes a huge JSON array of log records using the streaming JsonGenerator, so the
* generator itself needs almost no heap. Deterministic (fixed seed): every run produces
* the same bytes, so every approach in {@link Scan} must report the same counts.
*
* Usage: GenerateHugeJson [file] [targetBytes]
* defaults: target/huge.json 1073741824 (1 GiB)
*/
public class GenerateHugeJson {
static final String[] SERVICES = {"auth", "billing", "cart", "catalog", "checkout", "gateway",
"inventory", "mailer", "orders", "search", "shipping", "users"};
static final String[] PLANS = {"free", "pro", "team", "enterprise"};
static final String[] MESSAGES = {
"request completed", "cache miss, loading from database", "connection pool at 80 percent",
"retrying upstream call", "payment authorised", "session refreshed", "slow query detected",
"user profile updated", "background job finished", "rate limit approaching"};
public static void main(String[] args) throws Exception {
File file = new File(args.length > 0 ? args[0] : "target/huge.json");
long target = args.length > 1 ? Long.parseLong(args[1]) : 1L << 30;
file.getAbsoluteFile().getParentFile().mkdirs();
SplittableRandom rnd = new SplittableRandom(42);
JsonFactory factory = new JsonFactory();
long start = System.nanoTime();
long id = 0;
CountingStream counter = new CountingStream(new BufferedOutputStream(new FileOutputStream(file), 1 << 16));
try (OutputStream out = counter;
JsonGenerator g = factory.createGenerator(ObjectWriteContext.empty(), out)) {
g.writeStartArray();
while (counter.count + g.streamWriteOutputBuffered() < target) {
int r = rnd.nextInt(100);
String level = r < 2 ? "ERROR" : r < 10 ? "WARN" : "INFO";
g.writeStartObject();
g.writeNumberProperty("id", id);
g.writeStringProperty("ts", "2026-10-" + String.format("%02d", 1 + (int) (id % 28))
+ "T" + String.format("%02d:%02d:%02d", (int) (id % 24), (int) (id % 60), (int) (id % 53)) + "Z");
g.writeStringProperty("level", level);
g.writeStringProperty("service", SERVICES[rnd.nextInt(SERVICES.length)]);
g.writeStringProperty("host", "node-" + rnd.nextInt(64));
g.writeStringProperty("message", MESSAGES[rnd.nextInt(MESSAGES.length)]
+ " [req=" + Long.toHexString(rnd.nextLong()) + "]");
g.writeNumberProperty("latencyMs", rnd.nextInt(2000));
g.writeName("user");
g.writeStartObject();
g.writeNumberProperty("id", rnd.nextInt(5_000_000));
g.writeStringProperty("name", "user" + rnd.nextInt(100_000));
g.writeStringProperty("plan", PLANS[rnd.nextInt(PLANS.length)]);
g.writeEndObject();
g.writeName("tags");
g.writeStartArray();
for (int t = 0; t < 3; t++) g.writeString("tag-" + rnd.nextInt(500));
g.writeEndArray();
g.writeEndObject();
id++;
}
g.writeEndArray();
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("wrote %s : %,d bytes (%.2f GiB), %,d records, %,d ms%n",
file, file.length(), file.length() / (double) (1L << 30), id, ms);
}
/** Counts bytes that have actually been handed to the file. */
static final class CountingStream extends java.io.FilterOutputStream {
long count;
CountingStream(OutputStream out) { super(out); }
@Override public void write(int b) throws java.io.IOException { out.write(b); count++; }
@Override public void write(byte[] b, int off, int len) throws java.io.IOException { out.write(b, off, len); count += len; }
}
}
@@ -0,0 +1,72 @@
package com.ankurm.jackson3.streaminghuge;
import tools.jackson.core.JsonParser;
import tools.jackson.core.JsonToken;
import tools.jackson.core.ObjectReadContext;
import tools.jackson.core.json.JsonFactory;
/**
* The classic streaming bug. The post's original loop ("walk each field until END_OBJECT")
* is correct for FLAT objects. The moment a record contains a nested object or array, the
* nested END_OBJECT ends the inner loop early and the parser state is one level out of step.
* This runs the original loop and the skipChildren() version over the same nested input.
*/
public class NestedTrap {
static final String JSON = """
[{"level":"INFO","user":{"id":1},"message":"started"},
{"level":"ERROR","user":{"id":2},"message":"database down"},
{"level":"ERROR","user":{"id":3},"message":"disk full"}]""";
public static void main(String[] args) {
System.out.println("expected: 2 ERROR records");
System.out.println();
System.out.println("-- original loop (flat objects only) --");
try { original(); } catch (RuntimeException e) {
System.out.println("threw " + e.getClass().getName());
}
System.out.println();
System.out.println("-- with skipChildren() --");
fixed();
}
static void original() {
int errorCount = 0;
int guard = 0; // not in the original: without it this loop never terminates (see the output)
try (JsonParser parser = new JsonFactory().createParser(ObjectReadContext.empty(), JSON)) {
parser.nextToken();
while (parser.nextToken() != JsonToken.END_ARRAY) {
if (++guard > 20) { System.out.println("guard tripped: nextToken() keeps returning null at end of input; the original loop would spin forever"); break; }
String logLevel = null, logMessage = null;
while (parser.nextToken() != JsonToken.END_OBJECT) {
if (++guard > 200) { System.out.println("guard tripped (inner loop)"); return; }
String fieldName = parser.currentName();
parser.nextToken();
if ("level".equals(fieldName)) logLevel = parser.getString();
else if ("message".equals(fieldName)) logMessage = parser.getString();
}
if ("ERROR".equals(logLevel)) { System.out.println("ERROR: " + logMessage); errorCount++; }
}
}
System.out.println("Total errors found: " + errorCount);
}
static void fixed() {
int errorCount = 0;
try (JsonParser parser = new JsonFactory().createParser(ObjectReadContext.empty(), JSON)) {
parser.nextToken();
while (parser.nextToken() == JsonToken.START_OBJECT) {
String logLevel = null, logMessage = null;
while (parser.nextToken() == JsonToken.PROPERTY_NAME) {
String fieldName = parser.currentName();
parser.nextToken();
if ("level".equals(fieldName)) logLevel = parser.getString();
else if ("message".equals(fieldName)) logMessage = parser.getString();
else parser.skipChildren(); // no-op for scalars, skips a whole {..} or [..]
}
if ("ERROR".equals(logLevel)) { System.out.println("ERROR: " + logMessage); errorCount++; }
}
}
System.out.println("Total errors found: " + errorCount);
}
}
@@ -0,0 +1,18 @@
package com.ankurm.jackson3.streaminghuge;
import tools.jackson.core.StreamReadConstraints;
/**
* Jackson 3 ships guard rails on what a parser will accept. None of them limits the total SIZE of a
* document by default, which is why a 1 GB file parses fine. Printed from the library, not from memory.
*/
public class ReadLimits {
public static void main(String[] args) {
StreamReadConstraints c = StreamReadConstraints.defaults();
System.out.println("maxNestingDepth = " + c.getMaxNestingDepth());
System.out.println("maxStringLength = " + c.getMaxStringLength());
System.out.println("maxNumberLength = " + c.getMaxNumberLength());
System.out.println("maxNameLength = " + c.getMaxNameLength());
System.out.println("maxDocumentLength = " + c.getMaxDocumentLength() + " (-1 = unlimited)");
}
}
@@ -0,0 +1,146 @@
package com.ankurm.jackson3.streaminghuge;
import tools.jackson.core.JsonParser;
import tools.jackson.core.JsonToken;
import tools.jackson.core.ObjectReadContext;
import tools.jackson.core.json.JsonFactory;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
import java.io.File;
import java.util.List;
/**
* The same job four ways (plus one deliberately broken variant): count the ERROR records in a huge JSON array and sum their latency.
*
* stream JsonParser, token by token, skipChildren() for fields we do not need
* hybrid JsonParser walks the array; each element is bound to a record, then discarded
* tree JsonMapper.readTree(file) -> the whole document as JsonNode objects
* bind JsonMapper.readValue(file, List<LogEntry>) -> the whole document as records
*
* Usage: Scan {stream|hybrid|hybrid-naive|tree|bind} file
* Prints exactly one result line. A sampler thread records the peak of (total - free) heap,
* which INCLUDES garbage not yet collected, so for the streaming modes it overstates the
* live data. Run with different -Xmx values; see scripts/bench.sh.
*/
public class Scan {
public record User(long id, String name, String plan) { }
public record LogEntry(long id, String ts, String level, String service, String host,
String message, int latencyMs, User user, List<String> tags) { }
static volatile long peakUsed;
public static void main(String[] args) throws Exception {
String mode = args[0];
File file = new File(args[1]);
Runtime rt = Runtime.getRuntime();
Thread sampler = new Thread(() -> {
while (true) {
long used = rt.totalMemory() - rt.freeMemory();
if (used > peakUsed) peakUsed = used;
try { Thread.sleep(10); } catch (InterruptedException e) { return; }
}
});
sampler.setDaemon(true);
sampler.start();
long start = System.nanoTime();
try {
long[] r = switch (mode) {
case "stream" -> stream(file);
case "hybrid" -> hybrid(file);
case "hybrid-naive" -> hybridNaive(file);
case "tree" -> tree(file);
case "bind" -> bind(file);
default -> throw new IllegalArgumentException(mode);
};
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("%-7s -Xmx=%5d MB OK records=%,d errors=%,d errLatencySum=%,d %,7d ms peakUsed=%,5d MB%n",
mode, rt.maxMemory() >> 20, r[0], r[1], r[2], ms, peakUsed >> 20);
} catch (OutOfMemoryError oom) {
long ms = (System.nanoTime() - start) / 1_000_000;
// Drop references before printing so the message itself can allocate.
System.out.printf("%-7s -Xmx=%5d MB FAIL java.lang.OutOfMemoryError: %s after %,d ms%n",
mode, rt.maxMemory() >> 20, oom.getMessage(), ms);
System.exit(3);
}
}
/** Pure streaming: no object is ever built for a record. */
static long[] stream(File file) {
long records = 0, errors = 0, latency = 0;
try (JsonParser p = new JsonFactory().createParser(ObjectReadContext.empty(), file)) {
if (p.nextToken() != JsonToken.START_ARRAY) throw new IllegalStateException("expected array");
while (p.nextToken() == JsonToken.START_OBJECT) { // one record
records++;
String level = null;
int lat = 0;
while (p.nextToken() == JsonToken.PROPERTY_NAME) { // one field of the record
String name = p.currentName();
p.nextToken(); // move onto the value
switch (name) {
case "level" -> level = p.getString();
case "latencyMs" -> lat = p.getIntValue();
default -> p.skipChildren(); // nested user{} / tags[] skipped whole
}
}
if ("ERROR".equals(level)) { errors++; latency += lat; }
}
}
return new long[]{records, errors, latency};
}
/**
* The obvious hybrid, and a trap: mapper.readValue(parser, type) is a whole-document call. After the
* first record it sees the next START_OBJECT and, because FAIL_ON_TRAILING_TOKENS is on, throws.
*/
static long[] hybridNaive(File file) {
JsonMapper mapper = JsonMapper.builder().build();
long records = 0, errors = 0, latency = 0;
try (JsonParser p = mapper.createParser(file)) {
if (p.nextToken() != JsonToken.START_ARRAY) throw new IllegalStateException("expected array");
while (p.nextToken() == JsonToken.START_OBJECT) {
LogEntry e = mapper.readValue(p, LogEntry.class);
records++;
if ("ERROR".equals(e.level())) { errors++; latency += e.latencyMs(); }
}
}
return new long[]{records, errors, latency};
}
/** Streaming over the array, data binding per element: convenient and still flat on memory. */
static long[] hybrid(File file) {
JsonMapper mapper = JsonMapper.builder().build();
long records = 0, errors = 0, latency = 0;
try (JsonParser p = mapper.createParser(file)) {
if (p.nextToken() != JsonToken.START_ARRAY) throw new IllegalStateException("expected array");
while (p.nextToken() == JsonToken.START_OBJECT) {
LogEntry e = p.readValueAs(LogEntry.class); // binds exactly this object, nothing after it
records++;
if ("ERROR".equals(e.level())) { errors++; latency += e.latencyMs(); }
}
}
return new long[]{records, errors, latency};
}
/** Whole document as a tree. */
static long[] tree(File file) {
JsonNode root = JsonMapper.builder().build().readTree(file);
long records = 0, errors = 0, latency = 0;
for (JsonNode n : root) {
records++;
if ("ERROR".equals(n.path("level").asString())) { errors++; latency += n.path("latencyMs").asInt(); }
}
return new long[]{records, errors, latency};
}
/** Whole document as a List of records. */
static long[] bind(File file) {
List<LogEntry> all = JsonMapper.builder().build().readValue(file, new TypeReference<List<LogEntry>>() { });
long errors = 0, latency = 0;
for (LogEntry e : all) if ("ERROR".equals(e.level())) { errors++; latency += e.latencyMs(); }
return new long[]{all.size(), errors, latency};
}
}
@@ -0,0 +1,54 @@
package com.ankurm.jackson3.streaminghuge;
import tools.jackson.core.JacksonException;
import tools.jackson.core.JsonParser;
import tools.jackson.core.JsonToken;
import tools.jackson.core.ObjectReadContext;
import tools.jackson.core.json.JsonFactory;
import tools.jackson.databind.json.JsonMapper;
/**
* A streaming parser acts on records before it has seen the end of the file. If the file is cut
* off (a failed upload, a full disk) you have ALREADY processed the early records when the
* exception arrives. A tree or data-binding read fails before returning anything.
* Also shows that Jackson 3's exceptions are unchecked (JacksonException extends RuntimeException).
*/
public class TruncatedFile {
public static void main(String[] args) {
String full = """
[{"id":1,"level":"ERROR"},{"id":2,"level":"INFO"},{"id":3,"level":"ERROR"},{"id":4,"level":"ERROR"}]""";
String cut = full.substring(0, full.length() - 25);
System.out.println("input (truncated): " + cut);
System.out.println();
System.out.println("-- streaming --");
int errors = 0;
try (JsonParser p = new JsonFactory().createParser(ObjectReadContext.empty(), cut)) {
p.nextToken();
while (p.nextToken() == JsonToken.START_OBJECT) {
String level = null;
while (p.nextToken() == JsonToken.PROPERTY_NAME) {
String n = p.currentName();
p.nextToken();
if ("level".equals(n)) level = p.getString();
}
if ("ERROR".equals(level)) { errors++; System.out.println("handled an ERROR record, running total " + errors); }
}
} catch (JacksonException e) {
System.out.println("exception : " + e.getClass().getName());
System.out.println("is unchecked: " + (e instanceof RuntimeException));
System.out.println("first line: " + e.getOriginalMessage());
System.out.println("records already handled before the exception: " + errors);
}
System.out.println();
System.out.println("-- readTree --");
try {
JsonMapper.builder().build().readTree(cut);
} catch (JacksonException e) {
System.out.println("exception : " + e.getClass().getName());
System.out.println("records handled: 0 (no tree was returned)");
}
}
}