objectmapper-jsonmapper: Jackson 2.23.0 vs 3.3.0 side by side (ObjectMapper/JsonMapper guide rewrite)

Seven runnable programs P01-P07 plus five compile-failure files, JDK 25, no docs/ folder.
Output in objectmapper-jsonmapper/output/ is regenerated by scripts/run-all.sh.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b75Ao6imWN5bj7FHVw
This commit is contained in:
2026-11-17 00:53:38 +05:30
co-authored by Claude Sonnet 5.5
parent 1d0cd8b36e
commit f5ed5d1605
26 changed files with 857 additions and 0 deletions
@@ -0,0 +1,31 @@
package com.ankurm.objectmapper;
import java.util.List;
/**
* The plain POJO used by every example in this module. It carries NO Jackson annotations,
* so the same class is read and written by Jackson 2 and Jackson 3 without any change.
*/
public class Article {
private Long articleId;
private String title;
private List<String> tags;
private String subtitle; // left null on purpose in most examples
public Article() { } // Jackson needs a no-arg constructor for a bean like this
public Article(Long articleId, String title, List<String> tags) {
this.articleId = articleId;
this.title = title;
this.tags = tags;
}
public Long getArticleId() { return articleId; }
public void setArticleId(Long articleId) { this.articleId = articleId; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public List<String> getTags() { return tags; }
public void setTags(List<String> tags) { this.tags = tags; }
public String getSubtitle() { return subtitle; }
public void setSubtitle(String subtitle) { this.subtitle = subtitle; }
}
@@ -0,0 +1,45 @@
package com.ankurm.objectmapper;
import java.util.List;
/** The same write + read with Jackson 2's ObjectMapper and Jackson 3's JsonMapper. */
public class P01TwoMappersSideBySide {
public static void main(String[] args) throws Exception {
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json"));
// ---- Jackson 2: package com.fasterxml.jackson.databind ----
com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper();
String json2 = m2.writeValueAsString(article);
// ---- Jackson 3: package tools.jackson.databind.json ----
tools.jackson.databind.json.JsonMapper m3 = tools.jackson.databind.json.JsonMapper.builder().build();
String json3 = m3.writeValueAsString(article);
System.out.println("Jackson 2 " + m2.version() + " -> " + json2);
System.out.println("Jackson 3 " + m3.version() + " -> " + json3);
System.out.println("identical JSON: " + json2.equals(json3));
System.out.println();
// Reading back is the same call in both.
Article back2 = m2.readValue(json2, Article.class);
Article back3 = m3.readValue(json3, Article.class);
System.out.println("Jackson 2 read title: " + back2.getTitle());
System.out.println("Jackson 3 read title: " + back3.getTitle());
System.out.println();
// Pretty printing: Jackson 3 takes the feature on the builder, or per call on a writer.
String pretty3 = m3.writerWithDefaultPrettyPrinter().writeValueAsString(article);
System.out.println(pretty3);
System.out.println();
// Which classes are these, really?
System.out.println("m2 class: " + m2.getClass().getName());
System.out.println("m3 class: " + m3.getClass().getName());
System.out.println("m3 superclass: " + m3.getClass().getSuperclass().getName());
System.out.println("m3 is-a tools.jackson.databind.ObjectMapper: "
+ (m3 instanceof tools.jackson.databind.ObjectMapper));
// The annotation package is shared between the two majors.
System.out.println("@JsonInclude lives in: "
+ com.fasterxml.jackson.annotation.JsonInclude.class.getPackageName());
}
}
@@ -0,0 +1,58 @@
package com.ankurm.objectmapper;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
import com.fasterxml.jackson.annotation.JsonInclude;
/** Why Jackson 3 removed the setters: configuring a Jackson 2 mapper after first use is unreliable. */
public class P02ImmutableMapper {
private static List<String> mutators(Class<?> c) {
return new TreeSet<>(Arrays.stream(c.getMethods())
.map(Method::getName)
.filter(n -> n.startsWith("set") || n.equals("configure") || n.equals("enable")
|| n.equals("disable") || n.startsWith("register") || n.equals("addMixIn")
|| n.startsWith("activateDefaultTyping") || n.equals("findAndRegisterModules"))
.toList()).stream().toList();
}
public static void main(String[] args) throws Exception {
System.out.println("== public mutator methods on the mapper class ==");
System.out.println("Jackson 2 ObjectMapper : "
+ mutators(com.fasterxml.jackson.databind.ObjectMapper.class).size() + " distinct names");
System.out.println("Jackson 3 ObjectMapper : "
+ mutators(tools.jackson.databind.ObjectMapper.class).size() + " distinct names");
System.out.println("Jackson 3 JsonMapper : "
+ mutators(tools.jackson.databind.json.JsonMapper.class).size() + " distinct names");
System.out.println(" the one Jackson 3 name that matched: " + mutators(tools.jackson.databind.ObjectMapper.class)
+ " (a getter, not a setter)");
System.out.println();
Article withNull = new Article(1L, "Jackson Deep Dive", List.of("java")); // subtitle == null
// ---- Jackson 2: change the inclusion rule AFTER the mapper has already serialised an Article ----
com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper();
System.out.println("== Jackson 2: reconfigure after first use ==");
System.out.println("before : " + m2.writeValueAsString(withNull));
m2.setSerializationInclusion(JsonInclude.Include.NON_NULL);
System.out.println("after setSerializationInclusion(NON_NULL) : " + m2.writeValueAsString(withNull));
com.fasterxml.jackson.databind.ObjectMapper fresh2 = new com.fasterxml.jackson.databind.ObjectMapper();
fresh2.setSerializationInclusion(JsonInclude.Include.NON_NULL);
System.out.println("fresh mapper, same setting : " + fresh2.writeValueAsString(withNull));
System.out.println();
// ---- Jackson 3: the mapper is final-config; derive a new one with rebuild() ----
tools.jackson.databind.json.JsonMapper m3 = tools.jackson.databind.json.JsonMapper.builder().build();
System.out.println("== Jackson 3: rebuild() derives a new mapper ==");
System.out.println("original : " + m3.writeValueAsString(withNull));
tools.jackson.databind.json.JsonMapper nonNull = m3.rebuild()
.changeDefaultPropertyInclusion(i -> i.withValueInclusion(JsonInclude.Include.NON_NULL))
.build();
System.out.println("rebuilt NON_NULL : " + nonNull.writeValueAsString(withNull));
System.out.println("original again : " + m3.writeValueAsString(withNull));
System.out.println("same instance? : " + (m3 == nonNull));
}
}
@@ -0,0 +1,103 @@
package com.ankurm.objectmapper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectReader;
import tools.jackson.databind.json.JsonMapper;
/** Every way in and out, on Jackson 3. One mapper, built once. */
public class P03ReadWriteCookbook {
public static void main(String[] args) throws Exception {
JsonMapper mapper = JsonMapper.builder().build();
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json"));
// ---- WRITE ----
String asString = mapper.writeValueAsString(article);
byte[] asBytes = mapper.writeValueAsBytes(article);
Path file = Files.createTempFile("article", ".json");
mapper.writeValue(file, article); // Path (java.nio)
mapper.writeValue(file.toFile(), article); // File
ByteArrayOutputStream out = new ByteArrayOutputStream();
mapper.writeValue(out, article); // OutputStream
System.out.println("writeValueAsString : " + asString);
System.out.println("writeValueAsBytes : " + asBytes.length + " bytes");
System.out.println("writeValue(Path) : " + Files.readString(file));
System.out.println("writeValue(Stream) : " + out.size() + " bytes");
System.out.println();
// ---- READ ----
System.out.println("read String : " + mapper.readValue(asString, Article.class).getTitle());
System.out.println("read byte[] : " + mapper.readValue(asBytes, Article.class).getTitle());
System.out.println("read File : " + mapper.readValue(file.toFile(), Article.class).getTitle());
System.out.println("read Path : " + mapper.readValue(file, Article.class).getTitle());
System.out.println("read InputStream : "
+ mapper.readValue(new ByteArrayInputStream(asBytes), Article.class).getTitle());
System.out.println("read Reader : "
+ mapper.readValue(new StringReader(asString), Article.class).getTitle());
Files.delete(file);
System.out.println();
// ---- GENERIC TYPES: a Class<T> cannot carry List<Article>, a TypeReference can ----
String array = "[{\"articleId\":1,\"title\":\"First\"},{\"articleId\":2,\"title\":\"Second\"}]";
List<Article> list = mapper.readValue(array, new TypeReference<List<Article>>() { });
System.out.println("List<Article> size : " + list.size() + ", element class: " + list.get(0).getClass().getSimpleName());
List<?> raw = mapper.readValue(array, List.class);
System.out.println("List.class element : " + raw.get(0).getClass().getName());
System.out.println();
// ---- TREE and convertValue ----
JsonNode tree = mapper.readTree(asString);
System.out.println("tree title : " + tree.get("title").asString());
System.out.println("tree tags[1] : " + tree.get("tags").get(1).asString());
Map<String, Object> asMap = mapper.convertValue(article, new TypeReference<Map<String, Object>>() { });
System.out.println("convertValue to Map : " + asMap);
Article fromMap = mapper.convertValue(Map.of("articleId", 9, "title", "From a Map"), Article.class);
System.out.println("convertValue to bean : " + fromMap.getArticleId() + " / " + fromMap.getTitle());
System.out.println();
// ---- Reusable reader / writer: cheap, thread-safe, fixed to one type ----
ObjectReader articleReader = mapper.readerFor(Article.class);
Article viaReader = articleReader.readValue(asString);
System.out.println("readerFor(Article) : " + viaReader.getTitle());
System.out.println("pretty writer : "
+ mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Map.of("k", 1)).replace("\n", "\\n"));
System.out.println();
// ---- Is there a readValue(URL) in each major? ----
System.out.println("Jackson 2 readValue(URL, Class) exists : " + hasUrlOverload(
com.fasterxml.jackson.databind.ObjectMapper.class));
System.out.println("Jackson 3 readValue(URL, Class) exists : " + hasUrlOverload(
tools.jackson.databind.ObjectMapper.class));
System.out.println("Jackson 3 readTree(URL) exists : " + Arrays.stream(
tools.jackson.databind.ObjectMapper.class.getMethods())
.filter(m -> m.getName().equals("readTree"))
.anyMatch(m -> m.getParameterCount() == 1 && m.getParameterTypes()[0] == java.net.URL.class));
String marathi = "\u092e\u0930\u093e\u0920\u0940"; // five Devanagari code points
byte[] utf8 = mapper.writeValueAsBytes(new Article(2L, marathi, null));
System.out.println("non-ASCII byte[] round trip equal : "
+ mapper.readValue(utf8, Article.class).getTitle().equals(marathi)
+ " (bytes are " + StandardCharsets.UTF_8.name() + " by default: "
+ new String(utf8, StandardCharsets.UTF_8).contains(marathi) + ")");
}
private static boolean hasUrlOverload(Class<?> mapperClass) {
for (Method m : mapperClass.getMethods()) {
if (m.getName().equals("readValue") && m.getParameterCount() == 2
&& m.getParameterTypes()[0] == java.net.URL.class) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,93 @@
package com.ankurm.objectmapper;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.PropertyNamingStrategies;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.cfg.DateTimeFeature;
import tools.jackson.databind.json.JsonMapper;
/** The configuration most projects actually need, and what the two majors default to. */
public class P04ConfigRecipes {
public static void main(String[] args) throws Exception {
// ---- 1. Defaults, read from the enums themselves (nothing typed by hand) ----
System.out.println("== default value of a few features (enabledByDefault) ==");
System.out.printf("%-52s %-8s %-8s%n", "feature", "Jackson2", "Jackson3");
row("DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES",
com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault(),
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault());
row("SerializationFeature.FAIL_ON_EMPTY_BEANS",
com.fasterxml.jackson.databind.SerializationFeature.FAIL_ON_EMPTY_BEANS.enabledByDefault(),
SerializationFeature.FAIL_ON_EMPTY_BEANS.enabledByDefault());
row("SerializationFeature.INDENT_OUTPUT",
com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT.enabledByDefault(),
SerializationFeature.INDENT_OUTPUT.enabledByDefault());
row("WRITE_DATES_AS_TIMESTAMPS (J2: SerializationFeature, J3: DateTimeFeature)",
com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault(),
DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault());
row("DeserializationFeature.FAIL_ON_TRAILING_TOKENS",
com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS.enabledByDefault(),
DeserializationFeature.FAIL_ON_TRAILING_TOKENS.enabledByDefault());
row("MapperFeature.SORT_PROPERTIES_ALPHABETICALLY",
com.fasterxml.jackson.databind.MapperFeature.SORT_PROPERTIES_ALPHABETICALLY.enabledByDefault(),
tools.jackson.databind.MapperFeature.SORT_PROPERTIES_ALPHABETICALLY.enabledByDefault());
System.out.println();
// ---- 2. The behaviour behind the first row ----
String withExtra = "{\"articleId\":1,\"title\":\"T\",\"views\":42}"; // 'views' is not on Article
try {
new com.fasterxml.jackson.databind.ObjectMapper().readValue(withExtra, Article.class);
System.out.println("Jackson 2 default : accepted unknown field");
} catch (Exception e) {
System.out.println("Jackson 2 default : " + e.getClass().getSimpleName());
}
Article ok = JsonMapper.builder().build().readValue(withExtra, Article.class);
System.out.println("Jackson 3 default : accepted unknown field, title=" + ok.getTitle());
try {
JsonMapper.builder().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build()
.readValue(withExtra, Article.class);
} catch (Exception e) {
System.out.println("Jackson 3 strict : " + e.getClass().getSimpleName());
}
try {
JsonMapper.builderWithJackson2Defaults().build().readValue(withExtra, Article.class);
System.out.println("builderWithJackson2Defaults : accepted unknown field");
} catch (Exception e) {
System.out.println("builderWithJackson2Defaults : " + e.getClass().getSimpleName() + " (Jackson 2 behaviour back)");
}
System.out.println();
// ---- 2b. Property order: Jackson 3 sorts alphabetically by default, Jackson 2 follows the class ----
Article ordered = new Article(1L, "T", List.of("a"));
ordered.setSubtitle("S");
System.out.println("order J2 default : "
+ new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(ordered));
System.out.println("order J3 default : " + JsonMapper.builder().build().writeValueAsString(ordered));
System.out.println("order J3 sorting disabled : " + JsonMapper.builder()
.disable(tools.jackson.databind.MapperFeature.SORT_PROPERTIES_ALPHABETICALLY).build()
.writeValueAsString(ordered));
System.out.println("order J3 Jackson2Defaults : "
+ JsonMapper.builderWithJackson2Defaults().build().writeValueAsString(ordered));
System.out.println();
// ---- 3. The recipe: one shared, immutable mapper for an application ----
JsonMapper mapper = JsonMapper.builder()
.enable(SerializationFeature.INDENT_OUTPUT) // pretty output
.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) // articleId -> article_id
.changeDefaultPropertyInclusion(
i -> i.withValueInclusion(JsonInclude.Include.NON_NULL)) // skip nulls
.build();
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json")); // subtitle is null
String json = mapper.writeValueAsString(article);
System.out.println(json);
Article back = mapper.readValue(json, Article.class);
System.out.println("round trip articleId = " + back.getArticleId());
}
private static void row(String name, boolean j2, boolean j3) {
System.out.printf("%-52s %-8s %-8s%n", name, j2, j3);
}
}
@@ -0,0 +1,57 @@
package com.ankurm.objectmapper;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Map;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import tools.jackson.databind.json.JsonMapper;
/** java.time: an extra module and a flag in Jackson 2, nothing at all in Jackson 3. */
public class P05JavaTime {
public static void main(String[] args) throws Exception {
Map<String, Object> payload = new java.util.LinkedHashMap<>();
payload.put("published", LocalDate.of(2026, 11, 17));
payload.put("at", Instant.parse("2026-11-17T00:47:00Z"));
// Jackson 2, plain mapper: java.time is rejected outright (since 2.12).
com.fasterxml.jackson.databind.ObjectMapper plain2 = new com.fasterxml.jackson.databind.ObjectMapper();
try {
plain2.writeValueAsString(payload);
} catch (Exception e) {
System.out.println("Jackson 2, no module : " + e.getClass().getSimpleName());
System.out.println(" " + e.getMessage().lines().findFirst().orElse(""));
}
// Jackson 2 with the module: dates become number ARRAYS and a timestamp unless you also flip a flag.
com.fasterxml.jackson.databind.ObjectMapper module2 = new com.fasterxml.jackson.databind.ObjectMapper()
.registerModule(new JavaTimeModule());
System.out.println("Jackson 2 + JavaTimeModule : " + module2.writeValueAsString(payload));
com.fasterxml.jackson.databind.ObjectMapper fixed2 = new com.fasterxml.jackson.databind.ObjectMapper()
.registerModule(new JavaTimeModule())
.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
System.out.println("Jackson 2 + module + disable(TIMESTAMPS): " + fixed2.writeValueAsString(payload));
// Jackson 3: no module, no flag.
JsonMapper m3 = JsonMapper.builder().build();
System.out.println("Jackson 3, plain JsonMapper : " + m3.writeValueAsString(payload));
// And it reads back.
LocalDate back = m3.readValue("\"2026-11-17\"", LocalDate.class);
System.out.println("Jackson 3 read LocalDate : " + back);
// Does the module still exist for Jackson 3?
for (String cls : new String[] {
"tools.jackson.datatype.jsr310.JavaTimeModule",
"com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"}) {
try {
Class.forName(cls);
System.out.println("class present on classpath : " + cls);
} catch (ClassNotFoundException e) {
System.out.println("class NOT on classpath : " + cls);
}
}
}
}
@@ -0,0 +1,60 @@
package com.ankurm.objectmapper;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.json.JsonMapper;
/** Checked in Jackson 2, unchecked in Jackson 3. Same malformed input, both mappers. */
public class P06Exceptions {
public static void main(String[] args) {
String malformed = "{\"articleId\": 1, \"title\": }";
String wrongType = "{\"articleId\": \"not-a-number\"}";
com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper();
JsonMapper m3 = JsonMapper.builder().build();
System.out.println("== class hierarchy ==");
System.out.println("J2 JsonProcessingException extends " + com.fasterxml.jackson.core.JsonProcessingException.class
.getSuperclass().getName() + " -> extends "
+ com.fasterxml.jackson.core.JsonProcessingException.class.getSuperclass().getSuperclass().getName());
System.out.println("J3 JacksonException extends " + JacksonException.class.getSuperclass().getName());
System.out.println();
System.out.println("== malformed JSON ==");
try {
m2.readValue(malformed, Article.class);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) { // checked: the compiler forces this catch
System.out.println("J2 " + e.getClass().getName());
System.out.println(" " + e.getOriginalMessage());
System.out.println(" at line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr());
}
try {
m3.readValue(malformed, Article.class); // no throws clause needed on main()
} catch (JacksonException e) {
System.out.println("J3 " + e.getClass().getName());
System.out.println(" " + e.getOriginalMessage());
System.out.println(" at line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr());
}
System.out.println();
System.out.println("== wrong value type ==");
try {
m2.readValue(wrongType, Article.class);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
System.out.println("J2 " + e.getClass().getSimpleName());
}
try {
m3.readValue(wrongType, Article.class);
} catch (JacksonException e) {
System.out.println("J3 " + e.getClass().getSimpleName() + " (path: "
+ e.getPath().stream().map(r -> r.getPropertyName()).toList() + ")");
}
System.out.println();
// The whole point: a lambda body may now call the mapper with no try/catch.
java.util.List<Article> parsed = java.util.stream.Stream.of(
"{\"articleId\":1,\"title\":\"a\"}", "{\"articleId\":2,\"title\":\"b\"}")
.map(s -> m3.readValue(s, Article.class)) // does not compile on Jackson 2
.toList();
System.out.println("stream + lambda parsed " + parsed.size() + " articles with no try/catch");
}
}
@@ -0,0 +1,63 @@
package com.ankurm.objectmapper;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import tools.jackson.databind.json.JsonMapper;
/** One shared mapper across threads, versus building a mapper for every call. Timings are indicative. */
public class P07SharedMapperThreads {
static final int THREADS = 8;
static final int PER_THREAD = 20_000;
public static void main(String[] args) throws Exception {
JsonMapper shared = JsonMapper.builder().build();
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json"));
String json = shared.writeValueAsString(article);
// ---- correctness: many threads, one mapper ----
AtomicInteger wrong = new AtomicInteger();
runThreads(() -> {
for (int i = 0; i < PER_THREAD; i++) {
Article a = shared.readValue(json, Article.class);
if (!"Jackson Deep Dive".equals(a.getTitle()) || !shared.writeValueAsString(a).equals(json)) {
wrong.incrementAndGet();
}
}
});
System.out.println(THREADS + " threads x " + PER_THREAD + " round trips on ONE JsonMapper, wrong results: " + wrong.get());
System.out.println();
// ---- cost: shared mapper vs a new mapper per call (single thread, warm JVM) ----
int n = 2_000;
for (int round = 1; round <= 3; round++) { // three rounds so the JIT settles; read the last
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
shared.readValue(json, Article.class);
}
long sharedMs = (System.nanoTime() - t0) / 1_000_000;
t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
JsonMapper.builder().build().readValue(json, Article.class);
}
long perCallMs = (System.nanoTime() - t0) / 1_000_000;
System.out.println("round " + round + ": shared " + sharedMs + " ms, new mapper per call " + perCallMs
+ " ms (" + n + " reads each)");
}
}
private static void runThreads(ThrowingRunnable body) throws Exception {
List<Thread> threads = new ArrayList<>();
for (int t = 0; t < THREADS; t++) {
Thread th = Thread.ofPlatform().start(() -> {
try { body.run(); } catch (Exception e) { throw new RuntimeException(e); }
});
threads.add(th);
}
for (Thread th : threads) { th.join(); }
}
interface ThrowingRunnable { void run() throws Exception; }
}