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 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; } }