<?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 P99 Engineering on Medium]]></title>
        <description><![CDATA[Stories by P99 Engineering on Medium]]></description>
        <link>https://medium.com/@nik6?source=rss-aeb03a7cb48e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0ooa5CTLp8zC2gkdEQ8mHg.png</url>
            <title>Stories by P99 Engineering on Medium</title>
            <link>https://medium.com/@nik6?source=rss-aeb03a7cb48e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:25:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nik6/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[A Deep Dive into ClassLoader Contention in Java]]></title>
            <link>https://medium.com/@nik6/a-deep-dive-into-classloader-contention-in-java-a0415039b0c1?source=rss-aeb03a7cb48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0415039b0c1</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[jvm-class-loader]]></category>
            <dc:creator><![CDATA[P99 Engineering]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 13:35:35 GMT</pubDate>
            <atom:updated>2026-02-14T16:07:30.558Z</atom:updated>
            <content:encoded><![CDATA[<p>Last month, while investigating intermittent latency spikes in our reporting service, I discovered something that made me do a double-take: 102 threads blocked simultaneously, all waiting on the same lock. The culprit? A single line of code that looked completely innocent.</p><p>This is the story of how DatatypeFactory.newInstance() brought our high-throughput Java service to its knees, and the surprisingly simple fix that eliminated the problem entirely.</p><h3>The Discovery</h3><p>We run a reporting microservice at my org that handles around 800 requests per second. Users were occasionally reporting slow responses, but our dashboards showed everything within SLA. No alerts were firing. The service was “working fine.”</p><p>During a routine performance review, I pulled thread dumps from production. What I found was alarming:</p><pre>&quot;hystrix-SearchProviderGroup-1&quot; #1111 daemon prio=5<br>   java.lang.Thread.State: BLOCKED (on object monitor)<br>    at jdk.internal.loader.URLClassPath.getLoader(URLClassPath.java:425)<br>    - waiting to lock &lt;0x00000000846e4668&gt; (a jdk.internal.loader.URLClassPath)<br>    ...<br>    at javax.xml.datatype.FactoryFinder.findServiceProvider(FactoryFinder.java:287)<br>    at javax.xml.datatype.DatatypeFactory.newInstance(DatatypeFactory.java:169)</pre><p>102 threads. All BLOCKED. All waiting on the same lock: &lt;0x00000000846e4668&gt;.</p><h3>Understanding the Problem</h3><h3>What Does DatatypeFactory.newInstance() Actually Do?</h3><p>When you call DatatypeFactory.newInstance(), it looks simple enough:</p><pre>public XMLGregorianCalendar getXMLGregorianCalendarValue(Date date) {<br>    DatatypeFactory factory = DatatypeFactory.newInstance();<br>    GregorianCalendar cal = new GregorianCalendar();<br>    cal.setTime(date);<br>    return factory.newXMLGregorianCalendar(cal);<br>}</pre><p>But under the hood, this innocent-looking call triggers a complex chain of operations:</p><pre>DatatypeFactory.newInstance()<br>    └── FactoryFinder.find()<br>        └── FactoryFinder.findServiceProvider()<br>            └── ServiceLoader.load()<br>                └── ServiceLoader$LazyClassPathLookupIterator.hasNext()<br>                    └── ClassLoader.getResources(&quot;META-INF/services/...&quot;)<br>                        └── URLClassLoader.findResources()<br>                            └── URLClassPath.getLoader()  ← SYNCHRONIZED</pre><p>The URLClassPath.getLoader() method is synchronized. In Java 11, the relevant code looks like this:</p><pre>// From jdk.internal.loader.URLClassPath<br>private synchronized Loader getLoader(int index) {<br>    // ... loader lookup logic<br>}</pre><p>Every call to DatatypeFactory.newInstance() eventually hits this synchronized block. When you have hundreds of threads calling this method concurrently, they all queue up waiting for this single lock.</p><h3>The ServiceLoader Tax</h3><p>The Java ServiceLoader mechanism is designed for flexibility — it allows implementations to be discovered at runtime via META-INF/services files. But this flexibility comes at a cost:</p><ol><li>Classpath scanning: ServiceLoader iterates through all JARs looking for service provider files</li><li>ClassLoader synchronization: Resource lookup requires synchronized access to the URLClassPath</li><li>Repeated work: Without caching, this happens on every newInstance() call</li></ol><p>In our case, with 800 requests/second and multiple DatatypeFactory.newInstance() calls per request, we were hitting this synchronized block millions of times per hour.</p><h3>The Thread Dump Evidence</h3><p>Looking at the full thread dump, I found two distinct patterns of blocked threads:</p><p><strong>Pattern 1: DatatypeFactory contention (majority of blocked threads)</strong></p><pre>&quot;hystrix-SearchProviderGroup-1&quot; BLOCKED<br>    at jdk.internal.loader.URLClassPath.getLoader(URLClassPath.java:425)<br>    - waiting to lock &lt;0x00000000846e4668&gt;<br>    ...<br>    at javax.xml.datatype.DatatypeFactory.newInstance(DatatypeFactory.java:169)</pre><p><strong>Pattern 2: ClassLoader resource loading for file reads</strong></p><pre>&quot;https-jsse-nio-8443-exec-26&quot; BLOCKED<br>    at jdk.internal.loader.URLClassPath.getLoader(URLClassPath.java:425)<br>    - waiting to lock &lt;0x00000000846e4668&gt;<br>    ...<br>    at java.net.URLClassLoader.getResourceAsStream(URLClassLoader.java:322)</pre><p>Both patterns were competing for the same lock. The DatatypeFactory calls were creating a traffic jam, and our file reading operations were stuck in the same queue.</p><h3>The Data: Quantifying the Problem</h3><p>I ran a Splunk query to understand how often we were reading files 34 million reads of the same small JSON files in 12 hours. Each read hitting the ClassLoader. Each ClassLoader access potentially contending with DatatypeFactory.newInstance() calls.</p><h3>The Fix</h3><h3>Fix #1: Static DatatypeFactory Initialization</h3><p>The DatatypeFactory instance is thread-safe once created. There&#39;s no reason to create a new one for every call.</p><p><strong>Before</strong>:</p><pre>public XMLGregorianCalendar getXMLGregorianCalendarValue(Date date) {<br>    DatatypeFactory factory = DatatypeFactory.newInstance();<br>    GregorianCalendar cal = new GregorianCalendar();<br>    cal.setTime(date);<br>    return factory.newXMLGregorianCalendar(cal);<br>}</pre><p><strong>After:</strong></p><pre>private static final DatatypeFactory DATATYPE_FACTORY;<br><br>static {<br>    try {<br>        DATATYPE_FACTORY = DatatypeFactory.newInstance();<br>    } catch (DatatypeConfigurationException e) {<br>        throw new RuntimeException(&quot;Failed to initialize DatatypeFactory&quot;, e);<br>    }<br>}<br><br>public XMLGregorianCalendar getXMLGregorianCalendarValue(Date date) {<br>    GregorianCalendar cal = new GregorianCalendar();<br>    cal.setTime(date);<br>    return DATATYPE_FACTORY.newXMLGregorianCalendar(cal);<br>}</pre><p>This single change eliminates all the ServiceLoader overhead after the first initialization. The factory is created once during class loading, and all subsequent calls use the cached instance.</p><h3>Fix #2: Caffeine Cache for File Contents</h3><p>For the file reading contention, I implemented a simple cache using Caffeine:</p><pre>@Component<br>@Slf4j<br>public class FileUtil {<br><br>    private static final int CACHE_MAX_SIZE = 100;<br>    private static final int CACHE_EXPIRE_AFTER_WRITE_MINUTES = 60;<br><br>    private final Cache&lt;String, String&gt; stringCache;<br><br>    public FileUtil() {<br>        this.stringCache = Caffeine.newBuilder()<br>                .maximumSize(CACHE_MAX_SIZE)<br>                .expireAfterWrite(CACHE_EXPIRE_AFTER_WRITE_MINUTES, TimeUnit.MINUTES)<br>                .build();<br>    }<br><br>    public String readFileAsString(Object classLoaderSource, String fileName) {<br>        String cachedValue = stringCache.getIfPresent(fileName);<br>        if (cachedValue != null) {<br>            return cachedValue;<br>        }<br><br>        String text = null;<br>        try (InputStream inputStream = classLoaderSource.getClass()<br>                .getClassLoader().getResourceAsStream(fileName)) {<br>            if (inputStream != null) {<br>                text = IOUtils.toString(inputStream, StandardCharsets.UTF_8);<br>                stringCache.put(fileName, text);<br>            }<br>        } catch (Exception e) {<br>            log.error(&quot;Error reading file={}&quot;, fileName, e);<br>        }<br>        return text;<br>    }<br>}</pre><h3>Why Caffeine?</h3><p>Caffeine uses a ConcurrentHashMap internally, which provides much finer-grained locking than the ClassLoader&#39;s URLClassPath:</p><pre>// From Caffeine&#39;s BoundedLocalCache<br>final ConcurrentHashMap&lt;Object, Node&lt;K, V&gt;&gt; data;</pre><h3>Deep Dive: Why Does This Happen?</h3><h3>The URLClassPath Lock</h3><p>In the JDK source code, URLClassPath maintains a list of Loader objects that know how to load resources from different URL types (JAR files, directories, etc.). The getLoader() method is synchronized because it lazily initializes these loaders:</p><pre>// Simplified from jdk.internal.loader.URLClassPath<br>private synchronized Loader getLoader(int index) {<br>    if (closed) {<br>        return null;<br>    }<br>    while (loaders.size() &lt; index + 1) {<br>        // Create new loader for next URL<br>        URL url = urls.get(loaders.size());<br>        Loader loader = getLoader(url);<br>        loaders.add(loader);<br>    }<br>    return loaders.get(index);<br>}</pre><p>This synchronization is necessary for thread-safety during lazy initialization, but it becomes a bottleneck when many threads are simultaneously trying to load resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jecxqRq6SiowpWYij9tQXQ.png" /></figure><h3>ServiceLoader’s Hidden Cost</h3><p>The ServiceLoader class, used by DatatypeFactory.newInstance(), iterates through all URLs in the classpath looking for service provider files:</p><pre>// From java.util.ServiceLoader<br>private class LazyClassPathLookupIterator implements Iterator&lt;Provider&lt;S&gt;&gt; {<br>    Enumeration&lt;URL&gt; configs;<br>    <br>    private boolean hasNextService() {<br>        while (configs == null || !configs.hasMoreElements()) {<br>            // Get next batch of service provider URLs<br>            configs = loader.getResources(PREFIX + service.getName());<br>        }<br>        // ...<br>    }<br>}</pre><p>Each getResources() call can trigger multiple URLClassPath.getLoader() calls as it searches through JARs. In a typical Spring Boot application with hundreds of JARs on the classpath, this adds up quickly.</p><h3>The Compounding Effect</h3><p>What made our situation particularly bad was the combination of:</p><ol><li>High concurrency: 800 requests/second with multiple threads per request</li><li>Repeated factory creation: DatatypeFactory.newInstance() called on every date conversion</li><li>Frequent file reads: 34 million file reads in 12 hours</li><li>Shared lock: Both operations competing for the same URLClassPath lock</li></ol><p>Each blocked thread holds onto memory and OS resources while waiting. With 102 threads blocked, we were wasting significant resources just waiting for lock acquisition.</p><h3>Results</h3><p>After deploying both fixes:</p><p>MetricBeforeAfterBlocked threads (peak)1020–2ClassLoader lock contentionHighNegligibleFile reads from classpath34M/12hr~100/hrDatatypeFactory instantiationsMillions1 (at startup)</p><p>The occasional 1–2 blocked threads we see now are during cache population on the first request for each file — expected behavior that resolves in milliseconds.</p><h3>Key Takeaways</h3><h3>1. Factory Methods Are Not Free</h3><p>Methods like DatatypeFactory.newInstance(), DocumentBuilderFactory.newInstance(), and TransformerFactory.newInstance() all use ServiceLoader internally. They&#39;re designed for flexibility, not performance. If you&#39;re calling them in a hot path, cache the result.</p><p>Other common offenders:</p><ul><li>SAXParserFactory.newInstance()</li><li>SchemaFactory.newInstance()</li><li>XPathFactory.newInstance()</li><li>XMLInputFactory.newInstance()</li></ul><h3>2. ClassLoader Operations Are Synchronized</h3><p>Any operation that touches the ClassLoader — getResource(), getResourceAsStream(), loadClass() - can potentially contend for locks. In high-throughput applications, minimize these operations in request-handling code.</p><h3>3. Thread Dumps Tell Stories</h3><p>Without thread dump analysis, this issue would have been nearly impossible to diagnose. The symptoms (occasional latency spikes) didn’t obviously point to ClassLoader contention. Regular thread dump analysis should be part of your performance monitoring toolkit.</p><h3>4. “Working Fine” Isn’t Good Enough</h3><p>Our service was meeting SLAs. No alerts were firing. But we were wasting enormous resources on unnecessary work. Performance optimization isn’t just about fixing broken things — it’s about not doing unnecessary work in the first place.</p><h3>5. Static Resources Should Be Cached</h3><p>If a file is baked into your JAR and never changes at runtime, read it once. This seems obvious, but it’s easy to miss when code is spread across multiple services and utility classes.</p><h3>How to Detect This in Your Application</h3><h3>Thread Dump Analysis</h3><p>Take thread dumps during peak load and look for:</p><ul><li>Multiple threads in BLOCKED state</li><li>Stack traces containing URLClassPath, ServiceLoader, or ClassLoader</li><li>Threads waiting on the same lock object</li></ul><h3>JFR (Java Flight Recorder)</h3><p>Enable JFR in production and look for:</p><ul><li>Lock contention events</li><li>High frequency of ClassLoader.getResource* calls</li><li>ServiceLoader activity</li></ul><pre>java -XX:StartFlightRecording=duration=60s,filename=recording.jfr ...</pre><h3>Conclusion</h3><p>A single line of code — DatatypeFactory.newInstance() - was causing 102 threads to block simultaneously in our production service. The fix was equally simple: initialize the factory once and reuse it.<br>Performance problems often hide in plain sight. The code looks correct. The tests pass. The service “works.” But under load, innocent-looking patterns can become severe bottlenecks.<br>Take the time to understand what your code is actually doing. Pull thread dumps. Question factory methods. Cache static resources. Your future self (and your on-call rotation) will thank you.<em>The code changes described in this article reduced ClassLoader contention by over 99% in our production environment. If you’re running a high-throughput Java service, I encourage you to check your thread dumps for similar patterns.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0415039b0c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>