<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by David Petro on Medium]]></title>
        <description><![CDATA[Stories by David Petro on Medium]]></description>
        <link>https://medium.com/@davidpetro?source=rss-67560147baa4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*earkwEj5_Xt__1RwCwYcJQ@2x.jpeg</url>
            <title>Stories by David Petro on Medium</title>
            <link>https://medium.com/@davidpetro?source=rss-67560147baa4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:39:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidpetro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Classloader That Killed Exactly One Kafka Producer]]></title>
            <link>https://medium.com/@davidpetro/the-classloader-that-killed-exactly-one-kafka-producer-14ef7664cc66?source=rss-67560147baa4------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ef7664cc66</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[David Petro]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 13:15:20 GMT</pubDate>
            <atom:updated>2026-08-11T13:15:20.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Eight Kafka producers. Seven fine. One broken 100% of the time. The difference was which thread called it first.</p><h3>It looked like a certificate problem</h3><p>We had spent most of that week on TLS certificate issues. So when this showed up in production logs, it slotted right into the story we were already telling ourselves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3MdUxiGn9bqCJJTPaemDg.png" /></figure><p>“Failed to construct kafka producer” reads like a broker you can’t reach, and with certificate work already in flight that’s where the conversation went first.</p><p>ClassNotFoundException means the immediate problem is class resolution, not broker connectivity. No socket was ever opened. The producer failed during linking, on a class that was inside the jar the whole time.</p><p>That distinction is worth being precise about, because getting it wrong is expensive rather than merely inaccurate: the two investigations share no evidence. Connectivity is answered with openssl s_client, broker logs, a packet capture. Resolution is answered with jar tf and the loader hierarchy. Commit to the wrong branch and every measurement you take afterwards is off the path — and the wrapper exception, which flattens both possibilities into one sentence, gives you nothing to correct course with.</p><h3>Four things that are individually defensible</h3><p>Three of these are beyond argument: documented, intentional, correct. The fourth I’d push back on, and I’ll come to that.</p><p><strong>One: the Oracle R2DBC driver completes its publishers on the common ForkJoinPool.</strong></p><p>Reactive drivers have to signal completion from somewhere, and this one uses the shared pool:</p><pre>PhasedPublisher$PhasedSubscription.emitComplete<br>  → java.util.concurrent.ForkJoinPool.runWorker</pre><p>Everything chained after a database query — every flatMap, every then — therefore runs on a common-pool thread unless you explicitly move it with publishOn. Most people never do, because most of the time it doesn&#39;t matter.</p><p><strong>Two: ForkJoin worker threads get the system classloader — whoever’s pool it is.</strong></p><p>DefaultForkJoinWorkerThreadFactory constructs its workers with useSystemClassLoader = true, and the constructor acts on it:</p><pre>// java.util.concurrent.ForkJoinWorkerThread  (JDK 17)<br>if (useSystemClassLoader)<br>    super.setContextClassLoader(ClassLoader.getSystemClassLoader());</pre><p>That’s deliberate. A work-stealing pool is shared infrastructure, and inheriting whatever the submitting thread happened to carry would leak application state between unrelated tasks.</p><p>I assumed for a while this was special to the <em>common</em> pool. It isn’t, and it’s worth correcting because the wrong version of this rule sends you looking for the wrong fix. Both factories pass true:</p><pre>// ForkJoinPool.DefaultForkJoinWorkerThreadFactory        — any pool you construct<br>new ForkJoinWorkerThread(null, pool, true, false);<br>// ForkJoinPool.DefaultCommonPoolForkJoinWorkerThreadFactory — the common pool<br>new ForkJoinWorkerThread(null, pool, true, true);</pre><p>Measured, with the submitting thread’s context classloader set to a distinctive marker:</p><pre>executor                          worker thread              context classloader<br>──────────────────────────────────────────────────────────────────────────────────<br>ForkJoinPool.commonPool()         commonPool-worker-1        SYSTEM<br>new ForkJoinPool(2)               ForkJoinPool-1-worker-1    SYSTEM<br>CompletableFuture.runAsync(...)   commonPool-worker-1        SYSTEM<br>Executors.newFixedThreadPool(1)   pool-1-thread-1            inherited from caller</pre><p>Identical on JDK 11, 17, 21 and 25.</p><p>The last row is the one that matters. Ordinary thread pools inherit the creating thread’s classloader; ForkJoin workers never do. So the same pipeline running on Schedulers.parallel() would not have broken — Reactor builds those on a plain ScheduledExecutorService with regular threads, which inherit LaunchedClassLoader and find everything. This bug needed the driver to complete on ForkJoin specifically. Not on &quot;a thread pool&quot;.</p><p><strong>Three: a Spring Boot fat jar hides its dependencies from that same system classloader.</strong></p><p>In an executable Spring Boot jar your dependencies aren’t on the classpath in any ordinary sense. They’re nested archives inside your archive:</p><pre>app.jar<br>├── org/springframework/boot/loader/launch/   ← visible to the System ClassLoader<br>│   ├── JarLauncher.class                         (the only real entry point)<br>│   └── LaunchedClassLoader.class<br>├── BOOT-INF/<br>│   ├── classes/                              ┐<br>│   │   └── com/acme/OrderService.class       │  visible ONLY to<br>│   └── lib/                                  │  LaunchedClassLoader<br>│       ├── kafka-clients-4.1.2.jar           │  (a nested jar — not a normal<br>│       │     └── ...JmxReporter.class        │   classpath entry; the JDK&#39;s<br>│       └── oracle-r2dbc.jar                  ┘   own loaders can&#39;t open these)<br>└── META-INF/MANIFEST.MF<br>      Main-Class:  org.springframework.boot.loader.launch.JarLauncher<br>      Start-Class: com.acme.Application<br>      Spring-Boot-Lib: BOOT-INF/lib/</pre><p>(That loader/launch/ package is Boot 3.2 and later. Before that it was loader/, and the class was called LaunchedURLClassLoader. If you&#39;re checking this against your own artifact — which you should, it&#39;s one unzip -l — the path moved.)</p><p>And the loader chain that results is asymmetric in a way that turns out to matter enormously:</p><pre>        ┌──────────────────────────────┐<br>        │   Bootstrap ClassLoader      │   java.lang.*, java.util.*<br>        └───────────────┬──────────────┘<br>                        │ parent<br>        ┌───────────────┴──────────────┐<br>        │   Platform ClassLoader       │   jdk.*, java.sql.*<br>        └───────────────┬──────────────┘<br>                        │ parent<br>        ┌───────────────┴──────────────┐<br>        │   System (App) ClassLoader   │ ←── the JVM puts THIS one on<br>        │   sees: app.jar root         │     ForkJoinPool worker threads<br>        │   CANNOT see BOOT-INF/lib/   │<br>        └───────────────┬──────────────┘<br>                        │ parent<br>        ┌───────────────┴──────────────┐<br>        │   LaunchedClassLoader        │ ←── what your application<br>        │   sees: BOOT-INF/classes/    │     actually runs on<br>        │         BOOT-INF/lib/*.jar   │<br>        └──────────────────────────────┘</pre><p>Delegation runs upward. A child asks its parent before searching itself, so LaunchedClassLoader can find everything the system classloader can find. The reverse never holds. A parent has no route into a child.</p><p>Land on a thread carrying the system classloader and you are sitting one level <em>below</em> your own dependencies with no way back up to them.</p><p><strong>Four: Kafka resolves reporter classes through the thread context classloader.</strong></p><p>Utils.getContextOrKafkaClassLoader(). The name is honest about it: current thread&#39;s context classloader first, Kafka&#39;s own only as a fallback.</p><p>Put the four together and you get a sentence that explains the whole outage:</p><blockquote><em>A Kafka producer built on a thread that just finished an Oracle query asks the </em>system<em> classloader for a class that only exists inside </em><em>BOOT-INF/lib/.</em></blockquote><h3>The one I’d argue with</h3><p>Facts two, three and four are simply how the platform works, and each is the right call in isolation. The first one I’d contest.</p><p>The common ForkJoinPool is sized and tuned for short, CPU-bound, non-blocking work. Handing user continuations back on it means an application’s flatMap — arbitrary code, written by someone with no idea where it will run — executes on a pool shared by every parallel stream, every CompletableFuture.supplyAsync, and every other library in the process that made the same assumption. One blocking call in one continuation starves all of them. The classloader surprise is the mild version of that problem; the version that actually keeps me up is a JDBC call or a block() inside a continuation quietly consuming a common-pool worker for two seconds.</p><p>Reactor’s own schedulers exist precisely so that continuations land somewhere with a known, sized, isolable identity. A driver that completes on the common pool opts every one of its users out of that, silently, and the only remedy available to them is an explicit publishOn they don&#39;t know they need.</p><p>So, three ingredients I’d defend, and one I’d call the actual mistake. The classloader failure is just the symptom that happened to be loud enough to trace.</p><h3>I called it a race condition, and lost a day to that</h3><p>My first hypothesis was a race. Something about startup ordering, intermittent, hard to pin down. I went looking for load correlations and time-of-day patterns.</p><p>There aren’t any. There’s nothing timing-dependent in this at all. If the calling thread is a common-pool thread, the context classloader is the system classloader, and the lookup fails. Every time. The producer had a 100% failure rate, not an elevated one, and every message on that path had been going nowhere.</p><p>Intermittent bugs and total-failure bugs want completely different investigations. I ran the wrong one for a while because “sometimes it works” felt more plausible than “this has never worked”, which is a bias worth naming: total failure in a system that appears to be running feels impossible, so you unconsciously downgrade it to partial failure and start looking for the trigger. There was no trigger.</p><h3>Seven producers were working by luck</h3><p>The service had eight KafkaTemplate beans. Seven were fine. The one publishing inventory items was completely dead.</p><p>The reason is an accident of ordering, and it’s the part of this I find genuinely interesting.</p><p>DefaultKafkaProducerFactory creates a producer lazily, on first send, and caches it for the life of the process. So whichever thread happens to trigger the <em>first</em> send decides whether that producer will ever work at all.</p><p>Seven of them got their first send from a Kafka listener thread, which carries the right classloader. Producer built, cached, healthy forever after — including for every later send from a common-pool thread, because those reuse the cached instance and load nothing.</p><p>The inventory-item producer never got that chance. Every path reaching it goes through an Oracle query first, so its first send always came from a common-pool thread. It was never constructed, so it was never cached, so it never recovered.</p><pre>PATH A — first send from a Kafka listener thread                    WORKS<br>─────────────────────────────────────────────────────────────────────────<br>  kafka-listener-0<br>    contextClassLoader = LaunchedClassLoader<br>        │<br>        ▼  template.send() → factory.createProducer()<br>        │<br>        ▼  Utils.getContextOrKafkaClassLoader()  →  LaunchedClassLoader<br>        │<br>        ▼  search BOOT-INF/lib/kafka-clients.jar  →  JmxReporter FOUND<br>        │<br>        ▼  producer CACHED in DefaultKafkaProducerFactory<br>           └─ every later send reuses it, from any thread,<br>              loading no classes at all  ──►  permanently healthy<br></pre><pre>PATH B — first send after an Oracle R2DBC query                    FAILS<br>────────────────────────────────────────────────────────────────────<br>  ForkJoinPool.commonPool-worker-3<br>    contextClassLoader = System ClassLoader   ← set by ForkJoinWorkerThread<br>        │<br>        ▼  PhasedSubscription.emitComplete()<br>        │  └─ your .flatMap() continuation resumes HERE<br>        │<br>        ▼  template.send() → factory.createProducer()<br>        │<br>        ▼  Utils.getContextOrKafkaClassLoader()  →  System ClassLoader<br>        │<br>        ▼  delegate up: Platform → Bootstrap        →  not found<br>        ▼  search itself: app.jar root only         →  not found<br>           BOOT-INF/lib/ is not on its search path<br>        │<br>        ▼  ClassNotFoundException: JmxReporter<br>        ▼  wrapped as KafkaException: Failed to construct kafka producer<br>           └─ nothing cached  ──►  every subsequent send repeats this</pre><p>The same latent defect existed in all eight producers. Only one of them ever showed a symptom, and which one was decided by call ordering nobody had written down or thought about.</p><h3>Why an upgrade set it off</h3><p>The code had looked like this for a long time. What changed was kafka-clients, from 3.7.1 to 4.1.2.</p><p>We pulled apart the bytecode of CommonClientConfigs in both versions, counting references to JmxReporter:</p><p>Version References to JmxReporter in CommonClientConfigs 3.7.1 4 4.1.2 0</p><p>In 3.7.1 the class appears as a compiled type reference. In 4.1.2 it survives only as a string in a config default, instantiated reflectively. That sounds like a triviality. It is the entire bug:</p><pre>kafka-clients 3.7.1 — COMPILED REFERENCE<br>════════════════════════════════════════════════════════════════<br>CommonClientConfigs.class, constant pool:<br><br>    #n  = Class   #m        // org/apache/kafka/common/metrics/JmxReporter<br>    #m  = Utf8             &quot;org/apache/kafka/common/metrics/JmxReporter&quot;<br><br>bytecode:<br><br>    ldc  #n                 // pushes JmxReporter.class onto the stack<br><br>Resolution rule — JVMS §5.4.3.1:<br><br>    a symbolic reference in class D is resolved using<br>    THE DEFINING CLASSLOADER OF D<br><br>    D = CommonClientConfigs,  defined by LaunchedClassLoader<br>                              (it was loaded from BOOT-INF/lib/)<br>      ↓<br>    resolved by LaunchedClassLoader  →  FOUND<br><br>    ► The thread that executes this instruction is IRRELEVANT.<br>      Resolution is anchored to the class, at link time.<br><br><br>kafka-clients 4.1.2 — REFLECTIVE, BY NAME<br>════════════════════════════════════════════════════════════════<br>The class name survives only as a config default STRING:<br><br>    &quot;org.apache.kafka.common.metrics.JmxReporter&quot;<br>      ↓<br>    Utils.newInstance(String klass, Class&lt;T&gt; base)<br>      ↓<br>    Class.forName(klass, true, Utils.getContextOrKafkaClassLoader())<br>                               └──────────────┬──────────────────┘<br>                                              │<br>                        Thread.currentThread().getContextClassLoader()<br><br>    ► The thread that executes this is now EVERYTHING.<br>      Resolution is anchored to the CALLER, at run time.</pre><p>A constant-pool class entry isn’t just a faster lookup. It’s a different resolution <em>root</em>. An ldc of a class constant resolves once, against the defining loader of the class holding the instruction, and caches the result in that class&#39;s runtime constant pool. Class.forName(name, ..., someLoader) resolves every time, against whatever loader you hand it.</p><p>Moving a class name out of the constant pool and into a configuration string moves it from the first world into the second. On a plain classpath the two are indistinguishable, which is presumably why the change looked safe. On a fat jar with threads that don’t all carry the same classloader, one of them is immune to which thread you’re on and the other is completely at its mercy.</p><p>And this is the part I keep coming back to, because it’s the opposite of a careless change.</p><p>It has a name. KIP-830 introduced auto.include.jmx.reporter explicitly as a temporary measure, and said in the proposal itself that the config would be removed in 4.0, with JmxReporter becoming a default entry in metric.reporters instead. That plan sat in public for years. It shipped on schedule. Kafka 4.0&#39;s release notes list it under removals.</p><p>So this wasn’t missed in review. It was designed, announced, documented, and executed exactly as promised — and it was still, invisibly, a change in how a class gets resolved. Nobody writes “and this moves resolution from the defining classloader to the thread context classloader” in a KIP about making a metrics reporter configurable, because from inside the library that isn’t what you’re doing. You’re deleting a config flag.</p><p>The lesson isn’t “review harder.” It’s that a class name migrating from bytecode into configuration is a category change that no amount of care at the source will surface, and that only shows up in environments where those two resolution roots differ — which is to say, in a fat jar, on the wrong thread, in production.</p><p>One more detail from reconstructing the timeline, because it tripped us up: the commit landed in mid-July, but only reached the release branch three weeks later through a merge. Production was actually broken for four days, not three weeks. Commit date and deploy date are different questions and only one of them is the incident.</p><h3>The fix</h3><p>We shipped the small thing first, because production was broken and nobody wanted to spend that afternoon rearchitecting a reactive pipeline.</p><p>Build every producer at startup, on a thread whose classloader is right:</p><pre>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class KafkaProducerWarmUp {<br><br>  private final ApplicationContext applicationContext;<br>  <br>  @EventListener(ApplicationReadyEvent.class)<br>  @SuppressWarnings(&quot;rawtypes&quot;)<br>  public void warmUp() {<br>      Map&lt;String, KafkaTemplate&gt; kafkaTemplates =<br>              applicationContext.getBeansOfType(KafkaTemplate.class);<br>      log.info(&quot;[KAFKA][WARM_UP] creating producers at startup total={}&quot;, kafkaTemplates.size());<br>      kafkaTemplates.forEach(this::warmUp);<br>  }<br>  <br>  private void warmUp(String templateBeanName, KafkaTemplate&lt;?, ?&gt; template) {<br>      try {<br>          Producer&lt;?, ?&gt; producer = template.getProducerFactory().createProducer();<br>          log.info(&quot;[KAFKA][WARM_UP][OK] template={} producer={}&quot;,<br>                  templateBeanName, producer.getClass().getSimpleName());<br>      } catch (Exception e) {<br>          log.error(&quot;[KAFKA][WARM_UP][FAILED] template={} — producer not created at startup; &quot;<br>                  + &quot;sends issued from outside a listener thread may fail&quot;, templateBeanName, e);<br>      }<br>  }<br>}</pre><p>The startup thread carries LaunchedClassLoader. The factory caches what it builds. Every send after that reuses the same instance and loads nothing, from any thread.</p><p>Three small decisions in there took longer than the code.</p><p>It iterates KafkaTemplate, not ProducerFactory. One of our templates builds its factory inline without exposing it as a bean, so warming up factories would have quietly skipped exactly one producer and handed us a green log with the hole still open.</p><p>A failure is logged, not thrown. If warm-up breaks, behaviour degrades to what it was before this class existed and the error surfaces on first send. Startup doesn’t depend on it.</p><p>And the logging isn’t decoration. Startup now prints total=8 and eight [OK] lines. If it ever prints seven, someone can see it. Before, the only evidence a producer worked was a message eventually arriving, which tells you hours late, from a path that might not run today, and never at all for the one that&#39;s fully broken.</p><h3>It’s a patch, and I’d rather say so</h3><p>Warm-up fixes lazy initialisation of KafkaProducer. That is the entire scope of it.</p><p>Anything else in the process that resolves a class by name on a ForkJoin thread is sitting on the same mine. ServiceLoader.load() goes through the thread context classloader by default. So does a lot of plugin discovery, and every library that reads an implementation class out of a properties file. We got lucky that the noisy failure was also the cheap one.</p><p>Here’s what else was on the table.</p><p><strong>Move the continuation.</strong> The honest fix is publishOn right after the query, putting the pipeline back on a scheduler somebody actually chose:</p><pre>orderRepository.findById(id)<br>    .publishOn(Schedulers.boundedElastic())<br>    .flatMap(order -&gt; kafkaTemplate.send(TOPIC, order))</pre><p>I like this one. It addresses the thing I said was the real mistake instead of one of its symptoms, and it also protects you from the failure mode that worries me more: a blocking call in a continuation quietly eating a common-pool worker.</p><p>The problem is that it’s a habit, not a guarantee. Someone has to remember it at every point where a driver hands control back, and a missing publishOn looks exactly like one that was never needed. We&#39;re adding them where we can see them. I don&#39;t think we&#39;ll get them all.</p><p><strong>Run from a flat classpath.</strong> This is the suggestion I expect in the comments, and it’s right — with a caveat that cost me an hour.</p><p>If the app runs like this, none of the article applies to you:</p><pre>java -cp &quot;BOOT-INF/classes:BOOT-INF/lib/*&quot; com.acme.Application</pre><p>No LaunchedClassLoader, no nesting, no asymmetry. The system classloader sees everything, so the thread you land on stops mattering.</p><p>What I had assumed, and what turns out to be wrong, is that “extracting the jar” is one thing that behaves one way. It isn’t. Boot 3.3 moved the answer, and the two eras land on opposite sides of this bug.</p><p>The older layertools flow explodes the jar into layer directories, and the Dockerfile documented alongside it sets JarLauncher as the entry point. That rebuilds a LaunchedClassLoader over those directories exactly as it does over nested jars — same hierarchy, same invisible BOOT-INF/lib/, same bug. You get the layer caching you extracted for and none of the flattening you might have assumed came with it.</p><p>jarmode=tools extract, which replaced it in 3.3, genuinely flattens. I checked the artifact this time instead of trusting the name:</p><pre>$ java -Djarmode=tools -jar app.jar extract --destination .<br>$ unzip -p app.jar META-INF/MANIFEST.MF | grep -E &#39;Main-Class|Class-Path&#39;<br>Main-Class: com.acme.Application<br>Class-Path: lib/kafka-clients-4.1.2.jar lib/oracle-r2dbc.jar ...</pre><pre>$ unzip -l app.jar | grep -c LaunchedClassLoader<br>0</pre><p>Main-Class is the application, the dependencies sit in a plain lib/ on an ordinary Class-Path, and no loader class survives into the artifact. The --layers variant that the current Dockerfile guide recommends behaves identically — same flat manifest, and the spring-boot-loader/ layer it emits is empty. Nothing in this article can happen to either.</p><p>Which leaves the case that actually bit us, and it’s the boring one: java -jar app.jar. The unextracted fat jar, launched the way you launch it on a VM, in a plain container, or from an IDE run configuration. That&#39;s JarLauncher, that&#39;s LaunchedClassLoader, and that&#39;s where this whole article lives.</p><p>So don’t reason about which side you’re on from the name of the command. I did, and got it wrong in both directions before I ran it. The manifest is the only thing that will tell you, and asking the JVM directly is better still:</p><pre>@EventListener(ApplicationReadyEvent.class)<br>public void reportLoaderTopology() {<br>    ClassLoader system = ClassLoader.getSystemClassLoader();<br>    log.info(&quot;[LOADER] app={} system={} depsVisibleToSystem={}&quot;,<br>            getClass().getClassLoader(), system,<br>            system.getResource(&quot;org/apache/kafka/common/metrics/JmxReporter.class&quot;) != null);<br>}</pre><p>If that last flag is false, every by-name lookup in your process is one misplaced thread away from failing.</p><p>Would I go flat on a new service? Probably, yes. On this one it meant touching the launch command, the Dockerfile and whatever else has an opinion about Main-Class, in order to remove a failure mode nobody on the team had heard of the week before. We didn&#39;t do it. I&#39;m not certain that was right, but I&#39;d rather write down that we chose than pretend the small fix was the obvious one.</p><p><strong>Three things that look like fixes and aren’t.</strong></p><p>Setting metric.reporters explicitly changes nothing. It&#39;s still a class name resolved through the same call; you&#39;ve just supplied the string yourself.</p><p>Overriding the common pool’s factory with -Djava.util.concurrent.ForkJoinPool.common.threadFactory is a real lever everywhere except here. The JVM loads that factory through the system classloader — the one that can&#39;t see BOOT-INF/classes/ — so your factory class is exactly as invisible as JmxReporter was. What makes it worth mentioning is how it fails. The whole property block lives inside catch (Exception ignore):</p><pre>try {  // ignore exceptions in accessing/parsing properties<br>    ...<br>    fac = (ForkJoinWorkerThreadFactory)<br>        ClassLoader.getSystemClassLoader().loadClass(sf).getConstructor().newInstance();<br>    ...<br>} catch (Exception ignore) {<br>}</pre><p>So the load fails, the default factory is used, and the JVM starts cleanly while silently ignoring the flag you set. The code around it was rewritten between JDK 17 and 25. The swallow survived both.</p><p>And wrapping sends in setContextClassLoader works fine, right up until the call site somebody adds next quarter.</p><h3>The test that would have caught this, except it wouldn’t</h3><pre>@Test<br>void producerIsConstructibleFromAForkJoinThread() throws Exception {<br>    ForkJoinPool.commonPool()<br>        .submit(() -&gt; template.getProducerFactory().createProducer())<br>        .get();<br>}</pre><p>Four lines, reproduces the bug precisely, and it passes. On my machine, in the IDE, in CI.</p><p>Test runners put everything on a flat classpath — Gradle’s test task, Maven Surefire, the IDE, all of them. So does bootRun. So does any integration test that boots the context in-process. In all of them the system classloader can see every dependency, which means the two resolution roots this whole article is about are indistinguishable — which is, when you sit with it, the same reason the Kafka change looked harmless to the people who made it. Nobody in this story had an environment where the difference showed up.</p><p>There’s a subtler failure stacked underneath, and I only found it while building the measurement table earlier in this article. submit(...).get() does not guarantee the task runs on a pool thread at all: when you block on get(), the joining thread is permitted to execute the task itself rather than sit idle. My first version of that probe used submit().get() and dutifully reported the <em>caller&#39;s</em> classloader, because the work never left main. Forcing an actual worker takes execute() and a latch:</p><pre>var latch = new CountDownLatch(1);<br>ForkJoinPool.commonPool().execute(() -&gt; {<br>    // ... capture Thread.currentThread().getContextClassLoader() here<br>    latch.countDown();<br>});<br>latch.await();</pre><p>So the test above has two independent reasons to be worthless, and when I wrote it I knew about neither.</p><p>A test is only worth something against the packaged artifact, launched the way production launches it: build the jar, start it, hit a route that publishes after a database read, check the message lands. We haven’t built that yet. It’s on the list, under a few things that are both more urgent and more fun.</p><p>Which is about where I’d leave it. The warm-up isn’t in the codebase because it’s the correct fix. It’s there because I don’t trust us to catch the next one.</p><h3>What I’d tell myself at the start of that week</h3><p>Classify a failure before investigating it. ClassNotFoundException puts you in class resolution, not connectivity, and those two lines of inquiry share no instruments and no evidence. The danger of an ambient incident isn&#39;t that it&#39;s wrong — it&#39;s that it hands you a ready-made explanation at precisely the moment you&#39;re choosing which tools to pick up.</p><p>In a fat jar, the context classloader is rarely what you assume, and the rule is sharper than “threads are unpredictable”: ForkJoin workers <em>never</em> inherit it, ordinary thread pools <em>always</em> do. Anything reaching you through CompletableFuture, a parallel stream, or a library that completes on ForkJoin is running one loader below your own dependencies. Reactive pipelines make that much more likely, because the thread executing your code is chosen by whichever library completed last — which is not something you specified anywhere, and not something that shows up in a stack trace until it breaks.</p><p>Anything built lazily and cached forever inherits the context of its first caller. If that caller varies, correctness now depends on call ordering that exists nowhere in your design.</p><p>And when a system appears to be running, resist the pull toward “intermittent”. Sometimes it has simply never worked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ef7664cc66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring WebFlux and Pageable]]></title>
            <link>https://medium.com/@davidpetro/spring-webflux-and-pageable-be55104c234f?source=rss-67560147baa4------2</link>
            <guid isPermaLink="false">https://medium.com/p/be55104c234f</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[spring-data]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[David Petro]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 13:45:38 GMT</pubDate>
            <atom:updated>2023-07-22T14:08:50.133Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with Spring WebFlux, one of the issues that might arise is the use of the Pageable interface, a tool commonly used to handle data pagination. However, developers often encounter the following error when trying to implement it:</p><pre>java.lang.IllegalStateException: No primary or single unique constructor found for interface org.springframework.data.domain.Pageable<br><br></pre><p>This error occurs because Spring WebFlux attempts to instantiate the Pageable interface. As Pageable is an interface, it cannot be instantiated directly. Attempting to do so results in an IllegalStateException.</p><p>This highlights an important difference between Spring WebFlux, a tool for creating reactive web applications, and Spring MVC, a tool that facilitates the development of web applications. In Spring MVC, the parameters of a request that correspond to a Pageable are automatically mapped to an instance of this interface. However, this automatic mapping does not occur in Spring WebFlux.</p><p>To implement pagination functionality in Spring WebFlux, you will need to develop your own logic. One possible solution is to manually handle the request parameters and create the Pageable object yourself. Here’s an example of how this can be done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b99bc28f9b0315f5af086925d007ed46/href">https://medium.com/media/b99bc28f9b0315f5af086925d007ed46/href</a></iframe><p>Although manual handling may work for simple situations, it can become less efficient when trying to apply more complex features, such as multiple sorting conditions. Also, this implementation is not the cleanest and may end up bloating the code, especially in larger applications.</p><p>Given this scenario, you might be asking yourself: is there a more efficient way to implement Pageable with Spring WebFlux?</p><p>Indeed, there is a more efficient way. Below, I will present an alternative approach that I believe provides a better solution to this challenge. Our goal is always to explore new paths and deepen our knowledge, in search of the best practices to improve our development skills.</p><p>The new approach involves creating a class that implements the <strong>HandlerMethodArgumentResolver</strong> interface. This class will intercept and handle query parameters, creating a corresponding <strong>Pageable</strong> instance. Here is the implementation of the <strong>PageableHandlerMethodArgumentResolver</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73f498eff9ba2eb0329217461ad50990/href">https://medium.com/media/73f498eff9ba2eb0329217461ad50990/href</a></iframe><p>After creating the PageableHandlerMethodArgumentResolver, it needs to be configured as a bean. In this way, Spring WebFlux will be aware of its existence and will be able to use it to resolve Pageable arguments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8d1ef56b19f65977a09c5bbd9fcb7fe/href">https://medium.com/media/f8d1ef56b19f65977a09c5bbd9fcb7fe/href</a></iframe><p>With this configuration, the project will now be functioning with the Pageable interface. To test, you can make requests like in the examples below:</p><pre>curl -s &#39;localhost:9001/v1/customers?page=0&amp;size=6&amp;sort=age,asc&#39; | python -m json.tool<br><br>{<br>    &quot;content&quot;: [<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f34d4&quot;,<br>            &quot;name&quot;: &quot;Blake Spencer&quot;,<br>            &quot;email&quot;: &quot;blake.spencer@mail.com&quot;,<br>            &quot;age&quot;: 1<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f34ed&quot;,<br>            &quot;name&quot;: &quot;Makayla Byrd&quot;,<br>            &quot;email&quot;: &quot;makaylabyrd@gmail.com&quot;,<br>            &quot;age&quot;: 1<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f34cd&quot;,<br>            &quot;name&quot;: &quot;Colton Cash&quot;,<br>            &quot;email&quot;: &quot;coltoncash@yahoo.com&quot;,<br>            &quot;age&quot;: 3<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f3529&quot;,<br>            &quot;name&quot;: &quot;Leah Miles&quot;,<br>            &quot;email&quot;: &quot;miles@mail.com&quot;,<br>            &quot;age&quot;: 3<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f3492&quot;,<br>            &quot;name&quot;: &quot;Amelia Mcgowan&quot;,<br>            &quot;email&quot;: &quot;ameliamcgowan@mail.com&quot;,<br>            &quot;age&quot;: 4<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f34ea&quot;,<br>            &quot;name&quot;: &quot;Ava Powers&quot;,<br>            &quot;email&quot;: &quot;powers@yahoo.com&quot;,<br>            &quot;age&quot;: 4<br>        }<br>    ],<br>    &quot;pageable&quot;: {<br>        &quot;sort&quot;: {<br>            &quot;empty&quot;: false,<br>            &quot;sorted&quot;: true,<br>            &quot;unsorted&quot;: false<br>        },<br>        &quot;offset&quot;: 0,<br>        &quot;pageNumber&quot;: 0,<br>        &quot;pageSize&quot;: 6,<br>        &quot;paged&quot;: true,<br>        &quot;unpaged&quot;: false<br>    },<br>    &quot;totalPages&quot;: 1,<br>    &quot;totalElements&quot;: 6,<br>    &quot;last&quot;: true,<br>    &quot;size&quot;: 6,<br>    &quot;number&quot;: 0,<br>    &quot;sort&quot;: {<br>        &quot;empty&quot;: false,<br>        &quot;sorted&quot;: true,<br>        &quot;unsorted&quot;: false<br>    },<br>    &quot;numberOfElements&quot;: 6,<br>    &quot;first&quot;: true,<br>    &quot;empty&quot;: false<br>}</pre><pre>curl -s &#39;localhost:9001/v1/customers?page=0&amp;size=6&amp;sort=age,desc&#39; | python -m json.tool<br>{<br>    &quot;content&quot;: [<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f34bb&quot;,<br>            &quot;name&quot;: &quot;Ethan Goodman&quot;,<br>            &quot;email&quot;: &quot;goodman@gmail.com&quot;,<br>            &quot;age&quot;: 100<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f34d6&quot;,<br>            &quot;name&quot;: &quot;Reagan Chapman&quot;,<br>            &quot;email&quot;: &quot;chapman@yahoo.com&quot;,<br>            &quot;age&quot;: 100<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f3503&quot;,<br>            &quot;name&quot;: &quot;Aria Wise&quot;,<br>            &quot;email&quot;: &quot;aria.wise@mail.com&quot;,<br>            &quot;age&quot;: 98<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f34b6&quot;,<br>            &quot;name&quot;: &quot;Isaiah Moore&quot;,<br>            &quot;email&quot;: &quot;isaiahmoore@yahoo.com&quot;,<br>            &quot;age&quot;: 97<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f34d3&quot;,<br>            &quot;name&quot;: &quot;Evelyn Horton&quot;,<br>            &quot;email&quot;: &quot;horton@mail.com&quot;,<br>            &quot;age&quot;: 95<br>        },<br>        {<br>            &quot;id&quot;: &quot;64b9254d507c7865456f350b&quot;,<br>            &quot;name&quot;: &quot;Evan Lamb&quot;,<br>            &quot;email&quot;: &quot;evanlamb@gmail.com&quot;,<br>            &quot;age&quot;: 94<br>        }<br>    ],<br>    &quot;pageable&quot;: {<br>        &quot;sort&quot;: {<br>            &quot;empty&quot;: false,<br>            &quot;sorted&quot;: true,<br>            &quot;unsorted&quot;: false<br>        },<br>        &quot;offset&quot;: 0,<br>        &quot;pageNumber&quot;: 0,<br>        &quot;pageSize&quot;: 6,<br>        &quot;paged&quot;: true,<br>        &quot;unpaged&quot;: false<br>    },<br>    &quot;totalPages&quot;: 1,<br>    &quot;totalElements&quot;: 6,<br>    &quot;last&quot;: true,<br>    &quot;size&quot;: 6,<br>    &quot;number&quot;: 0,<br>    &quot;sort&quot;: {<br>        &quot;empty&quot;: false,<br>        &quot;sorted&quot;: true,<br>        &quot;unsorted&quot;: false<br>    },<br>    &quot;numberOfElements&quot;: 6,<br>    &quot;first&quot;: true,<br>    &quot;empty&quot;: false<br>}</pre><p>This approach provides a cleaner and more efficient way to implement pagination functionality in Spring WebFlux. With it, you can keep your code organized and focused, even when dealing with complex features.</p><p>I hope this exploration has offered new perspectives for your work with Spring WebFlux and the Pageable interface. Remember, the key to becoming a successful developer is an unending quest for learning and continuous improvement.</p><p>For a complete implementation of this approach, feel free to check out my <a href="https://github.com/davidpetro88/webflux-pageable">GitHub repository</a>. Your feedback and contributions are always welcome!”</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be55104c234f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>