<?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 Ankit Verma on Medium]]></title>
        <description><![CDATA[Stories by Ankit Verma on Medium]]></description>
        <link>https://medium.com/@ankit.dev273?source=rss-17c656b80fc6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PQvMz1KkHReD4Q9y8avtsQ.jpeg</url>
            <title>Stories by Ankit Verma on Medium</title>
            <link>https://medium.com/@ankit.dev273?source=rss-17c656b80fc6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:30:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankit.dev273/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[Records, Sealed Classes, and Pattern Matching: Java’s Data-Oriented Programming Shift]]></title>
            <link>https://medium.com/javarevisited/records-sealed-classes-and-pattern-matching-javas-data-oriented-programming-shift-822055ea773a?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/822055ea773a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 09:48:33 GMT</pubDate>
            <atom:updated>2026-11-07T09:48:33.816Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Java isn’t trying to be Kotlin anymore. It found its own modern identity, and it’s worth understanding why these three features were never designed to work in isolation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cRZakct9LD_HQmBY" /><figcaption>Photo by <a href="https://unsplash.com/@2ykang?utm_source=medium&amp;utm_medium=referral">2y.kang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This is Article 4 in the Java Evolution series. Article 3 covered Project Leyden and how the JVM is solving its startup problem. This article shifts from runtime mechanics to language design: the three features that gave Java a coherent, modern way to model data. Next in the series: </em><strong><em>The Java Memory Model: What Every Senior Engineer Needs to Know.</em></strong></p><p>For a long time, the criticism of Java’s data modeling was fair.</p><p>A simple immutable data holder took fifteen lines: a constructor, getters, equals(), hashCode(), toString(), all hand-written or generated by an IDE and then silently drifting out of sync whenever a field got added. Modeling &quot;this value is one of exactly these three kinds&quot; meant an abstract class, three subclasses, and no compiler help ensuring you handled all three anywhere you branched on the type. Developers coming from Kotlin, Scala, or TypeScript looked at this and asked why Java made something so basic so expensive.</p><p>Records (Java 16), sealed classes (Java 17), and pattern matching for switch (Java 21) answer that question. Individually, each is a useful feature. Together, they are a coherent style, usually called <strong>data-oriented programming</strong>, and understanding why they were designed as a set, not three unrelated conveniences, is what lets you actually use them well.</p><h3>Records: Data Carriers With Nothing to Hide</h3><p>A record is a class that is transparently, and only, its data.</p><pre>// Before records: 20+ lines for an immutable point<br>public final class Point {<br>    private final int x;<br>    private final int y;</pre><pre>    public Point(int x, int y) {<br>        this.x = x;<br>        this.y = y;<br>    }</pre><pre>    public int x() { return x; }<br>    public int y() { return y; }</pre><pre>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (!(o instanceof Point)) return false;<br>        Point p = (Point) o;<br>        return x == p.x &amp;&amp; y == p.y;<br>    }</pre><pre>    @Override<br>    public int hashCode() { return Objects.hash(x, y); }</pre><pre>    @Override<br>    public String toString() { return &quot;Point[x=&quot; + x + &quot;, y=&quot; + y + &quot;]&quot;; }<br>}</pre><pre>// After records: one line, identical semantics<br>public record Point(int x, int y) { }</pre><p>The compiler generates the constructor, the accessors (x() and y(), not getX(), deliberately breaking from JavaBean convention to signal these are data components, not mutable properties), equals(), hashCode(), and toString(), all based purely on the declared components.</p><p><strong>The word “transparent” here is doing real work.</strong> A record’s entire state is its components, visible through its accessors, and nothing else. This isn’t a style suggestion, it’s enforced: a record can’t extend another class (it implicitly extends Record), and every field it declares becomes a constructor parameter. You can&#39;t add hidden mutable state to a record and still have it behave like a record; the language actively resists it.</p><p><strong>Validation lives in a compact constructor:</strong></p><pre>public record Range(int min, int max) {<br>    public Range {  // no parameter list, no body assignment, just validation<br>        if (min &gt; max) {<br>            throw new IllegalArgumentException(&quot;min must not exceed max&quot;);<br>        }<br>    }<br>}</pre><p><strong>Records can still have behavior</strong>, just not hidden state:</p><pre>public record Range(int min, int max) {<br>    public int length() {<br>        return max - min;<br>    }</pre><pre>    public boolean contains(int value) {<br>        return value &gt;= min &amp;&amp; value &lt;= max;<br>    }<br>}</pre><p>The practical rule: reach for a record the moment a class’s job is to hold a fixed set of values and expose them, API responses, value objects, configuration snapshots, the key of a Map. The moment a class needs mutable internal state that isn&#39;t one of its public components, it isn&#39;t a record&#39;s job anymore, and forcing it into one fights the feature instead of using it.</p><h3>Sealed Interfaces: Closing a Hierarchy on Purpose</h3><p>Java’s class hierarchies have always been open by default. Anyone, anywhere, could write a new subclass of your interface, which is exactly right for frameworks and libraries, and exactly wrong for modeling a fixed, known set of cases.</p><pre>// A payment can be exactly one of these three kinds, and nothing else, ever<br>public sealed interface PaymentMethod<br>    permits CreditCard, BankTransfer, DigitalWallet { }</pre><pre>public record CreditCard(String number, String cvv) implements PaymentMethod { }<br>public record BankTransfer(String iban, String swift) implements PaymentMethod { }<br>public record DigitalWallet(String provider, String accountId) implements PaymentMethod { }</pre><p>sealed plus permits tells the compiler, explicitly, &quot;this is the complete list, forever, unless someone deliberately edits this exact file.&quot; Nobody in another package, another module, or another team&#39;s codebase can add a fourth implementation without touching this declaration. That constraint sounds restrictive. It&#39;s actually the entire point, and it&#39;s what makes the next feature possible.</p><p>(The permits clause is optional when the implementing classes are declared in the same file, which is the common case for a small, cohesive hierarchy, so the three records above would usually sit directly below the sealed interface declaration rather than being written out in permits.)</p><h3>Pattern Matching for Switch: The Compiler Checks Your Work</h3><p>Here’s where the previous two features stop being independently useful conveniences and start being a system.</p><pre>public BigDecimal calculateFee(PaymentMethod method) {<br>    return switch (method) {<br>        case CreditCard cc -&gt; cc.number().startsWith(&quot;4&quot;)<br>            ? BigDecimal.valueOf(0.029)<br>            : BigDecimal.valueOf(0.035);<br>        case BankTransfer bt -&gt; BigDecimal.valueOf(0.001);<br>        case DigitalWallet dw -&gt; BigDecimal.valueOf(0.015);<br>        // No default clause needed, and none allowed to be missing<br>    };<br>}</pre><p>Because PaymentMethod is sealed with exactly three permitted implementations, the compiler knows, at compile time, that these three case branches are exhaustive. If a fourth record is ever added to the permits list, every switch statement over PaymentMethod that lacks a case for it fails to compile, immediately, at the point of the incomplete switch, not at runtime when some unlucky input hits the missing branch.</p><p>This is the exhaustiveness checking that enum-based switches have always had, extended to a hierarchy of genuinely different shapes of data, not just named constants. It&#39;s also why the default clause disappears: a sealed hierarchy with every case covered has nothing left for default to catch, and the compiler enforces that too, refusing to let a now-unreachable default branch silently mask a future missing case.</p><p><strong>Pattern matching also destructures</strong>, pulling a record’s components directly into the case:</p><pre>public String describe(PaymentMethod method) {<br>    return switch (method) {<br>        case CreditCard(String number, String cvv) when number.startsWith(&quot;4&quot;) -&gt;<br>            &quot;Visa card ending in &quot; + number.substring(number.length() - 4);<br>        case CreditCard(String number, String cvv) -&gt;<br>            &quot;Card ending in &quot; + number.substring(number.length() - 4);<br>        case BankTransfer(String iban, String swift) -&gt;<br>            &quot;Transfer from &quot; + iban;<br>        case DigitalWallet(String provider, String accountId) -&gt;<br>            provider + &quot; wallet&quot;;<br>    };<br>}</pre><p>The when clause adds a guard condition beyond the type match itself, and the record&#39;s components are bound directly to local variables (number, cvv, iban) without a separate accessor call. Compare this to the pre-pattern-matching version: an instanceof check, an explicit cast, then manual field access, repeated for every branch, with no compiler guarantee you handled every subtype.</p><h3>How the Three Compose: A Realistic Refactor</h3><p>Here’s legacy code that models an API response the old way, and what each feature actually removes when applied together.</p><p><strong>Before:</strong></p><pre>public abstract class ApiResult {<br>    public abstract boolean isSuccess();<br>}</pre><pre>public class Success extends ApiResult {<br>    private final Object data;<br>    public Success(Object data) { this.data = data; }<br>    public Object getData() { return data; }<br>    @Override public boolean isSuccess() { return true; }<br>}</pre><pre>public class Failure extends ApiResult {<br>    private final String errorCode;<br>    private final String message;<br>    public Failure(String errorCode, String message) {<br>        this.errorCode = errorCode;<br>        this.message = message;<br>    }<br>    public String getErrorCode() { return errorCode; }<br>    public String getMessage() { return message; }<br>    @Override public boolean isSuccess() { return false; }<br>}</pre><pre>// Calling code: no compiler help, isSuccess() is a manual, error-prone discriminator<br>if (result.isSuccess()) {<br>    Success s = (Success) result;<br>    process(s.getData());<br>} else {<br>    Failure f = (Failure) result;<br>    log.error(&quot;{}: {}&quot;, f.getErrorCode(), f.getMessage());<br>}</pre><p><strong>After:</strong></p><pre>public sealed interface ApiResult permits Success, Failure { }<br>public record Success(Object data) implements ApiResult { }<br>public record Failure(String errorCode, String message) implements ApiResult { }</pre><pre>// Calling code: exhaustive, destructured, no manual casts, no isSuccess() to get out of sync<br>switch (result) {<br>    case Success(Object data) -&gt; process(data);<br>    case Failure(String errorCode, String message) -&gt; log.error(&quot;{}: {}&quot;, errorCode, message);<br>}</pre><p>Nine lines of declaration instead of twenty-plus. No isSuccess() boolean to accidentally leave out of sync with reality if a third result type is ever added, because there&#39;s no isSuccess() at all: the type itself is the discriminator, and the compiler enforces that every switch over it stays exhaustive as the hierarchy evolves.</p><h3>Refactoring Legacy Code: Where to Start</h3><p>This isn’t an all-or-nothing migration. The three features adopt independently, in order of how much structural change each requires:</p><ol><li><strong>Records first.</strong> Any existing immutable class with a constructor, final fields, and generated equals()/hashCode()/toString() is a direct, almost mechanical replacement. Lowest risk, no behavior change, pure reduction in code to maintain.</li><li><strong>Sealed interfaces next</strong>, on hierarchies that are already closed in practice (every implementation lives in your own codebase, nobody external extends them) but not closed in the type system. This is a declaration change with no runtime behavior change, it only adds compiler enforcement to a constraint that was already true informally.</li><li><strong>Pattern matching last</strong>, as you touch the call sites that branch on type. This is the step with the most line-level diff, but it’s also where the exhaustiveness checking starts paying for itself, because now every future addition to the sealed hierarchy surfaces every switch that needs updating, at compile time, in your IDE, before code review.</li></ol><h3>The Mental Model</h3><p>These three features were never meant to be evaluated separately. A record with no sealed hierarchy around it is just a terser class. A sealed interface with no pattern matching over it is just a restricted class hierarchy with no new capability. Put together, they describe a style where data is modeled as a closed set of transparent shapes, and the compiler, not a runtime check, not a code review comment, not a unit test, guarantees every place that branches on those shapes stays correct as the shapes change.</p><p>That’s the actual shift. Not “Java added some syntax sugar.” Java gave itself a way to make illegal states unrepresentable and incomplete logic a compile error, which is the same goal functional languages have chased for decades, reached through Java’s own object-oriented vocabulary instead of an import from somewhere else.</p><p><em>Next in the Java Evolution series: </em><strong><em>The Java Memory Model: What Every Senior Engineer Needs to Know</em></strong><em>, covering happens-before semantics, volatile vs synchronized vs Atomic</em>, and what the JIT compiler is actually allowed to reorder.*</p><h3>Beyond the Code: The Realities of Engineering</h3><p>Knowing when a record or a sealed interface is the right tool makes your code better. It doesn’t help when a senior teammate rejects your PR for “overusing pattern matching” based on a style preference from five years ago, and you have to make the case for a language feature in a code review instead of in a compiler.</p><p>I’ve distilled the unwritten rules of navigating software engineering careers into a practical field guide.</p><p>👉 <a href="https://ankitv2717.gumroad.com/"><strong>Get “Beyond the Offer Letter” on Gumroad here</strong></a> and learn how software companies actually work so you can accelerate your engineering career.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=822055ea773a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/records-sealed-classes-and-pattern-matching-javas-data-oriented-programming-shift-822055ea773a">Records, Sealed Classes, and Pattern Matching: Java’s Data-Oriented Programming Shift</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot and Dependency Injection: Beyond the Basics]]></title>
            <link>https://medium.com/javarevisited/spring-boot-and-dependency-injection-beyond-the-basics-dd11c5bd4d5a?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd11c5bd4d5a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 09:48:20 GMT</pubDate>
            <atom:updated>2026-11-07T09:48:20.224Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Constructor injection and </em><em>@Autowired are just the surface. Here&#39;s what senior engineers actually know about how beans get created, scoped, and wired together.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d1Epjp6aLpSdbrL5" /><figcaption>Photo by <a href="https://unsplash.com/@hngstrm?utm_source=medium&amp;utm_medium=referral">H&amp;CO</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This is Article 6 in the Spring Boot Essentials 2026 series. Article 5 covered how auto-configuration decides which beans exist before you write a single </em><em>@Bean method. This article goes further: once a bean is a candidate, what actually governs its lifecycle, its scope, and which implementation gets injected when more than one exists. Next in the series: </em><strong><em>Spring Data JPA in 2026: What You&#39;re Probably Doing Wrong.</em></strong></p><p>Every Spring Boot developer learns the same four lines in their first week:</p><pre>@Service<br>public class OrderService {<br>    private final PaymentClient paymentClient;<br>    public OrderService(PaymentClient paymentClient) {<br>        this.paymentClient = paymentClient;<br>    }<br>}</pre><p>Constructor injection, a final field, done. It works, and for a huge share of real code, that’s the whole story.</p><p>But it isn’t the whole story. The day you have two implementations of the same interface and the container can’t decide which one to inject, or a bean that needs to be recreated per request instead of once for the whole application, or two beans that depend on each other and the container seems to deadlock during startup, the four-line version stops being enough. This article covers the parts that actually come up in production code: bean scopes, circular dependency resolution, @Primary vs @Qualifier, lazy initialization, and the ApplicationContext lifecycle that ties it all together.</p><h3>Bean Scopes: Singleton Is the Default, Not the Only Option</h3><p>Every bean Spring creates has a scope: how many instances exist and when they’re created. Most developers only ever see one.</p><p><strong>Singleton (the default).</strong> One instance per ApplicationContext, created once, reused everywhere it&#39;s injected.</p><pre>@Service<br>public class OrderService {<br>    // One instance exists for the whole application<br>}</pre><p>This is correct for almost everything: services, repositories, configuration holders. It’s also the reason you should never store per-request mutable state as an instance field on a @Service. Thousands of concurrent requests share that single instance.</p><p><strong>Prototype.</strong> A new instance every time the bean is requested from the container.</p><pre>@Component<br>@Scope(&quot;prototype&quot;)<br>public class ReportBuilder {<br>    private List&lt;String&gt; sections = new ArrayList&lt;&gt;(); // safe here, each caller gets a fresh instance<br>}</pre><p>Rare in practice, because most “I need a fresh object” problems are better solved with a plain new ReportBuilder() call than a prototype-scoped bean. Reach for this only when the object needs dependency injection itself (it needs other beans wired into it) and also needs to be stateful per use.</p><p><strong>Request and Session scope.</strong> One instance per HTTP request, or per HTTP session, in a web application.</p><pre>@Component<br>@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)<br>public class RequestAuditContext {<br>    private String traceId;<br>    private String userId;<br>    // Populated once per request, safe to hold request-specific state<br>}</pre><p>The proxyMode = ScopedProxyMode.TARGET_CLASS is not optional decoration. A singleton bean that depends on a request-scoped bean can&#39;t just hold a direct reference, because that reference would be fixed to whichever request happened to be active at startup. Spring solves this by injecting a proxy: every method call on the proxy transparently resolves to the correct instance for the currently active request. Without the proxy mode declared, this fails at startup with a scope-mismatch error, not silently at runtime.</p><p><strong>The practical rule:</strong> stay with singleton unless you have an explicit, concrete reason not to. Request-scoped beans are the one exception that shows up regularly in real codebases, specifically for per-request context you don’t want to thread through every method signature manually.</p><h3>@Primary vs @Qualifier: Two Different Answers to &quot;Which One?&quot;</h3><p>The moment you have more than one implementation of an interface, injection by type alone becomes ambiguous.</p><pre>public interface NotificationSender {<br>    void send(String message);<br>}</pre><pre>@Component<br>public class EmailNotificationSender implements NotificationSender { /* ... */ }</pre><pre>@Component<br>public class SmsNotificationSender implements NotificationSender { /* ... */ }</pre><pre>@Service<br>public class AlertService {<br>    private final NotificationSender sender; // which one?</pre><pre>    public AlertService(NotificationSender sender) { this.sender = sender; }<br>}</pre><p>Spring Boot fails to start here, with NoUniqueBeanDefinitionException, because it has no basis to choose. Two mechanisms resolve this, and they answer different questions.</p><p><strong>@Primary</strong> answers: &quot;If nobody asks for a specific one, which is the default?&quot;</p><pre>@Component<br>@Primary<br>public class EmailNotificationSender implements NotificationSender { /* ... */ }</pre><p>Now every unqualified injection point gets the email sender. This is a decision made once, at the bean definition, and it applies everywhere that type is injected without further specification.</p><p><strong>@Qualifier</strong> answers: &quot;At this specific injection point, which exact one do I want?&quot;</p><pre>@Component(&quot;smsSender&quot;)<br>public class SmsNotificationSender implements NotificationSender { /* ... */ }</pre><pre>@Service<br>public class AlertService {<br>    private final NotificationSender sender;</pre><pre>    public AlertService(@Qualifier(&quot;smsSender&quot;) NotificationSender sender) {<br>        this.sender = sender;<br>    }<br>}</pre><p>@Qualifier overrides @Primary at the point it&#39;s used. Think of @Primary as a global fallback and @Qualifier as a local override, and reach for @Qualifier any time an injection point genuinely needs a specific implementation rather than whatever the default happens to be. Mixing both in the same codebase is normal: mark the common case @Primary, and qualify the exceptions explicitly.</p><p><strong>A cleaner alternative for more than two implementations:</strong> inject a List&lt;NotificationSender&gt; or Map&lt;String, NotificationSender&gt; and let the consuming code pick by business logic, rather than growing a long chain of @Qualifier-annotated constructor parameters.</p><pre>@Service<br>public class AlertService {<br>    private final Map&lt;String, NotificationSender&gt; sendersByChannel;</pre><pre>    public AlertService(Map&lt;String, NotificationSender&gt; sendersByChannel) {<br>        this.sendersByChannel = sendersByChannel; // keyed by bean name automatically<br>    }</pre><pre>    public void alert(String channel, String message) {<br>        sendersByChannel.get(channel).send(message);<br>    }<br>}</pre><h3>Circular Dependencies: The Problem Constructor Injection Exposes</h3><p>This is the failure mode constructor injection is actually designed to surface, not hide.</p><pre>@Service<br>public class OrderService {<br>    private final InventoryService inventoryService;<br>    public OrderService(InventoryService inventoryService) {<br>        this.inventoryService = inventoryService;<br>    }<br>}</pre><pre>@Service<br>public class InventoryService {<br>    private final OrderService orderService;<br>    public InventoryService(OrderService orderService) {<br>        this.orderService = orderService;<br>    }<br>}</pre><p>With constructor injection, this fails at startup with BeanCurrentlyInCreationException. To build OrderService, Spring needs InventoryService. To build InventoryService, Spring needs OrderService. Neither can finish constructing first.</p><p><strong>The wrong fix, field injection as a workaround:</strong></p><pre>@Service<br>public class OrderService {<br>    @Autowired<br>    private InventoryService inventoryService; // &quot;fixes&quot; the circularity, hides a design problem<br>}</pre><p>Field injection breaks the deadlock because Spring can construct the bean with no-args first and inject the field afterward. This “works.” It also means two services depend directly on each other, which is almost always a sign that a piece of shared logic belongs in a third class, or that an event should replace a direct call.</p><p><strong>The right fix, in order of preference:</strong></p><ol><li><strong>Extract the shared behavior into a third service</strong> that both OrderService and InventoryService depend on, breaking the cycle structurally rather than papering over it.</li><li><strong>Replace the direct call with an application event</strong>, if the second call doesn’t need an immediate return value:</li></ol><pre>@Service<br>public class OrderService {<br>    private final ApplicationEventPublisher events;</pre><pre>    public OrderService(ApplicationEventPublisher events) {<br>        this.events = events;<br>    }</pre><pre>    public void placeOrder(Order order) {<br>        // ... order logic ...<br>        events.publishEvent(new OrderPlacedEvent(order.getId()));<br>    }<br>}</pre><pre>@Service<br>public class InventoryService {<br>    @EventListener<br>    public void onOrderPlaced(OrderPlacedEvent event) {<br>        // react without OrderService ever depending on InventoryService&#39;s constructor<br>    }<br>}</pre><ol><li><strong>As a last resort</strong>, @Lazy on one side of the cycle defers that dependency&#39;s resolution until it&#39;s actually used, breaking the startup-time deadlock without going all the way to field injection:</li></ol><pre>public OrderService(@Lazy InventoryService inventoryService) {<br>    this.inventoryService = inventoryService; // resolved on first use, not at construction<br>}</pre><p>Treat @Lazy here as a temporary unblock, not a destination. The underlying design question (why do two services need each other directly) is still open.</p><h3>@Primary, @Lazy, and Bean Initialization Order</h3><p>Beyond resolving circular dependencies, @Lazy has a legitimate standalone use: deferring the cost of constructing an expensive bean until it&#39;s actually needed.</p><pre>@Component<br>@Lazy<br>public class ExpensiveReportingEngine {<br>    public ExpensiveReportingEngine() {<br>        // Loads a large model into memory, takes several seconds<br>    }<br>}</pre><p>Without @Lazy, every singleton bean is constructed during application startup, in an order Spring determines from the dependency graph. With @Lazy, this bean isn&#39;t constructed until the first time something actually asks for it. This trades slower first-use latency for faster startup, which matters for applications where cold-start time is a deployment concern (serverless, frequent restarts in Kubernetes) but the bean itself is rarely exercised.</p><p>It is not a substitute for @DependsOn, which exists for a different problem entirely: forcing one bean to be initialized before another when there&#39;s an ordering requirement that isn&#39;t visible through a direct dependency (a common case: a bean that reads a file another bean writes during its own initialization, with no direct injection relationship between them).</p><pre>@Component<br>@DependsOn(&quot;fileWriterBean&quot;)<br>public class FileReaderBean {<br>    // Guarantees fileWriterBean&#39;s initialization completes first,<br>    // even though FileReaderBean never injects it directly<br>}</pre><h3>The ApplicationContext Lifecycle, End to End</h3><p>Every bean scope, qualifier, and ordering rule above exists inside a larger sequence that runs once per application startup:</p><ol><li><strong>Bean definition loading.</strong> Spring reads @Component, @Service, @Repository, @Configuration, and auto-configuration classes, and builds a registry of bean <em>definitions</em>, metadata about what to create, not yet actual objects.</li><li><strong>BeanFactoryPostProcessor execution.</strong> Code that can modify bean definitions before any bean is instantiated, for example @ConfigurationProperties binding setup.</li><li><strong>Bean instantiation</strong>, in dependency order. A bean’s constructor runs only after all of its constructor-injected dependencies have themselves been fully constructed. This is exactly what the circular dependency section above collides with.</li><li><strong>BeanPostProcessor execution</strong>, around each bean&#39;s initialization. @PostConstruct-annotated methods run here, after construction and dependency injection, but before the bean is handed out to the rest of the application:</li></ol><pre>@Component<br>public class CacheWarmer {<br>    @PostConstruct<br>    public void warmCache() {<br>        // Runs after all dependencies are injected, before this bean is used anywhere<br>    }<br>}</pre><ol><li><strong>The </strong><strong>ApplicationContext is fully initialized.</strong> ApplicationReadyEvent fires. This is the correct hook for &quot;run this once, after everything is wired and ready,&quot; rather than @PostConstruct on some arbitrary bean that happens to run late in the sequence:</li></ol><pre>@Component<br>public class StartupTask {<br>    @EventListener(ApplicationReadyEvent.class)<br>    public void onReady() {<br>        // The entire application context is guaranteed to be ready here<br>    }<br>}</pre><ol><li><strong>Shutdown.</strong> @PreDestroy-annotated methods, and DisposableBean.destroy() implementations, run in reverse dependency order as the context closes, giving beans a chance to release connections, flush buffers, or deregister from external systems before the JVM exits.</li></ol><p>Most Spring Boot developers interact with steps 3 and 4 constantly without naming them. Knowing the full sequence is what turns “my @PostConstruct method failed because a dependency wasn&#39;t ready yet&quot; from a mystery into an ordering problem you can reason about directly.</p><h3>The Mental Model</h3><p>Dependency injection in Spring Boot isn’t just “the container hands you your dependencies.” It’s a managed lifecycle with explicit rules at every stage: how many instances exist (scope), which one you get when there’s a choice (@Primary and @Qualifier), what happens when two beans need each other (circular dependency resolution), when a bean actually gets built (lazy initialization and @DependsOn), and what runs at each point in that sequence (the ApplicationContext lifecycle).</p><p>Constructor injection and @Autowired get you through most of a career. The rest of this list is what you reach for on the day the simple case breaks, and knowing it before that day arrives is the difference between debugging the container and debugging your own design.</p><p><em>Next in the Spring Boot Essentials 2026 series: </em><strong><em>Spring Data JPA in 2026: What You’re Probably Doing Wrong</em></strong><em>, covering the N+1 query problem, fetch strategies, and what Hibernate 7’s session API changes actually mean for your repositories.</em></p><h3>Beyond the Code: The Realities of Engineering</h3><p>Understanding bean scopes and the ApplicationContext lifecycle makes you a better engineer. It doesn&#39;t tell you how to push back when a teammate&#39;s circular dependency &quot;fix&quot; is field injection papering over a design problem, and the PR is already approved by someone else.</p><p>I’ve distilled the unwritten rules of navigating software engineering careers into a practical field guide.</p><p>👉 <a href="https://ankitv2717.gumroad.com/"><strong>Get “Beyond the Offer Letter” on Gumroad here</strong></a> and learn how software companies actually work so you can accelerate your engineering career.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd11c5bd4d5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-boot-and-dependency-injection-beyond-the-basics-dd11c5bd4d5a">Spring Boot and Dependency Injection: Beyond the Basics</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Spring Boot Auto-Configuration Actually Works]]></title>
            <link>https://medium.com/javarevisited/how-spring-boot-auto-configuration-actually-works-8c3faaa8184d?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c3faaa8184d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 15:24:43 GMT</pubDate>
            <atom:updated>2026-11-04T15:24:43.124Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You’ve typed </em><em>@SpringBootApplication thousands of times. Here&#39;s what it&#39;s actually doing on your behalf, and why that matters the day it stops cooperating.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WjiZFMThXDNyH3FO" /><figcaption>Photo by <a href="https://unsplash.com/@randyfath?utm_source=medium&amp;utm_medium=referral">Randy Fath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This is Article 5 in the Spring Boot Essentials 2026 series. Article 4 covered Virtual Threads and what changes for your code under load. This article goes one layer deeper, into the machinery that decides which beans exist in your application before you write a single </em><em>@Bean method. Next in the series: </em><strong><em>Spring Boot and Dependency Injection: Beyond the Basics.</em></strong></p><p>Every Spring Boot developer has had this moment.</p><p>You add a dependency, say spring-boot-starter-data-redis, to your POM. You restart the application. And suddenly a RedisTemplate bean exists, fully configured, ready to inject. You didn&#39;t write a configuration class. You didn&#39;t call new. You didn&#39;t wire anything.</p><p>Most developers shrug and move on. It works, so why ask questions.</p><p>But the day it <em>doesn’t</em> work, the day your custom DataSource bean silently gets overridden or two starters fight over the same bean and your application fails to start with a wall of red text, that shrug stops being good enough. You need to know what auto-configuration actually is, because the failure modes only make sense once you do.</p><p>This article covers the real mechanism: how @EnableAutoConfiguration works, how Spring Boot 4 finds auto-configuration classes, the @Conditional system that decides what actually gets created, how to write your own auto-configuration, and how to debug the whole thing when it disagrees with you.</p><h3>The Annotation That Does Almost Nothing Itself</h3><p>Start with @SpringBootApplication. It looks like one annotation. It is three:</p><pre>@SpringBootApplication<br>// is exactly equivalent to:<br>@SpringBootConfiguration   // a specialized @Configuration<br>@EnableAutoConfiguration   // the one that matters here<br>@ComponentScan             // scans your package for @Component, @Service, etc.<br>public class MyApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MyApplication.class, args);<br>    }<br>}</pre><p>@SpringBootConfiguration just marks the class as a configuration source: it does no scanning, no conditional logic. @ComponentScan finds <em>your</em> beans. Neither of these is where the magic lives.</p><p>The magic is @EnableAutoConfiguration. That&#39;s the annotation responsible for the RedisTemplate showing up unasked.</p><h3>How Auto-Configuration Classes Are Found</h3><p>Here is the part most developers never look at: how does Spring Boot know <em>which</em> classes to even consider auto-configuring?</p><p><strong>Before Spring Boot 2.7</strong>, the answer was a file at META-INF/spring.factories:</p><pre># META-INF/spring.factories, the legacy mechanism<br>org.springframework.boot.autoconfigure.EnableAutoConfiguration=\<br>com.example.redis.RedisAutoConfiguration,\<br>com.example.redis.RedisRepositoriesAutoConfiguration</pre><p>Every starter JAR on your classpath could list its auto-configuration classes in this file. Spring Boot read all of them, from every JAR, at startup.</p><p><strong>Since Spring Boot 2.7, and as the only mechanism in Spring Boot 4</strong>, this moved to a dedicated file:</p><pre>META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports</pre><pre># AutoConfiguration.imports, one fully-qualified class name per line<br>com.example.redis.RedisAutoConfiguration<br>com.example.redis.RedisRepositoriesAutoConfiguration</pre><p>This is not a cosmetic rename. spring.factories was a general-purpose extension file: auto-configuration classes were mixed in alongside ApplicationListeners, EnvironmentPostProcessors, and other extension points, all under different keys in the same giant properties file. Spring Boot had to parse the whole thing and filter by key every time.</p><p>AutoConfiguration.imports holds <em>only</em> auto-configuration class names, one per line, nothing else. Startup scanning is faster, and more importantly for Spring Boot 4, this format is what makes <strong>ahead-of-time (AOT) processing</strong> possible. A flat list of class names can be resolved once at build time and baked into a native image or an AOT-processed JAR. A giant multi-purpose properties file can&#39;t be optimized the same way.</p><p><strong>If you’re maintaining a library with custom auto-configuration:</strong> spring.factories entries under the EnableAutoConfiguration key stopped being read in Spring Boot 4. If your own starter still uses the old file, your auto-configuration silently never runs: no error, no warning. Migrate it:</p><pre># Find the old-style registration<br>grep -r &quot;EnableAutoConfiguration=&quot; --include=&quot;spring.factories&quot; .</pre><p>Move those class names into META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, one per line, and delete the old key from spring.factories.</p><h3>Collecting Candidates Is Not the Same as Creating Beans</h3><p>Here’s the detail that trips people up: Spring Boot doesn’t create every auto-configuration class it finds. It <em>collects</em> them (potentially hundreds, across every starter on the classpath) and then filters almost all of them out before a single bean is instantiated.</p><p>The filter is the @Conditional system.</p><pre>// A real (simplified) auto-configuration class<br>@AutoConfiguration<br>@ConditionalOnClass(RedisConnectionFactory.class)<br>@EnableConfigurationProperties(RedisProperties.class)<br>public class RedisAutoConfiguration {</pre><pre>    @Bean<br>    @ConditionalOnMissingBean(RedisTemplate.class)<br>    public RedisTemplate&lt;Object, Object&gt; redisTemplate(<br>            RedisConnectionFactory connectionFactory) {<br>        RedisTemplate&lt;Object, Object&gt; template = new RedisTemplate&lt;&gt;();<br>        template.setConnectionFactory(connectionFactory);<br>        return template;<br>    }<br>}</pre><p>Two conditions are doing real work here, and they answer two different questions:</p><p><strong>@ConditionalOnClass(RedisConnectionFactory.class)</strong>, is answered at the <em>class</em> level: &quot;Does a Redis client library even exist on this classpath?&quot; If you never added spring-boot-starter-data-redis, RedisConnectionFactory doesn&#39;t exist, the condition fails, and the entire RedisAutoConfiguration class is skipped: no beans inside it are even evaluated. This is also why auto-configuration adds almost no startup cost for starters you don&#39;t use: the condition check is a cheap classpath lookup, not a full bean evaluation.</p><p><strong>@ConditionalOnMissingBean(RedisTemplate.class)</strong>, is answered at the <em>bean</em> level: &quot;Has the user already defined their own RedisTemplate?&quot; If you wrote your own @Bean public RedisTemplate&lt;...&gt; redisTemplate(...), Spring Boot&#39;s version backs off entirely. Yours wins. This is the mechanism behind the rule every Spring Boot developer has internalized without necessarily knowing why: <strong>your explicit configuration always overrides auto-configuration.</strong> It&#39;s not a priority system or a precedence number; it&#39;s just this one condition, used consistently across every starter.</p><p>The other conditions worth knowing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Mof7WWtaI7jmDYj42HZjpA.png" /></figure><p>Every one of these is evaluated <em>before</em> any bean is created, and the evaluation is cheap: a classpath check, a property lookup, a context query. This is why you can have 150+ auto-configuration classes on your classpath and your application still starts in under a second: almost all of them get filtered out at the condition-check stage, long before the expensive part (actually instantiating a bean) happens.</p><h3>Writing Your Own Auto-Configuration</h3><p>You don’t need to be building a public starter library to benefit from this. Internal platform teams use the exact same mechanism to ship shared configuration (a standard RestClient setup, a company-wide tracing configuration, a default ObjectMapper) across every microservice in an organization, without every team copy-pasting a @Configuration class.</p><p><strong>Step 1: Write the configuration class, annotated with </strong><strong>@AutoConfiguration</strong> (not plain @Configuration, this marks it as something Spring Boot&#39;s auto-configuration ordering machinery is aware of):</p><pre>@AutoConfiguration<br>@ConditionalOnClass(RestClient.class)<br>@EnableConfigurationProperties(CompanyHttpProperties.class)<br>public class CompanyHttpClientAutoConfiguration {</pre><pre>    @Bean<br>    @ConditionalOnMissingBean<br>    public RestClient.Builder companyRestClientBuilder(CompanyHttpProperties props) {<br>        return RestClient.builder()<br>            .requestFactory(new JdkClientHttpRequestFactory())<br>            .requestInterceptor((request, body, execution) -&gt; {<br>                request.getHeaders().add(&quot;X-Company-Trace-Id&quot;, TraceContext.current());<br>                return execution.execute(request, body);<br>            })<br>            .requestInterceptor(new RetryInterceptor(props.getMaxRetries()));<br>    }<br>}</pre><p><strong>Step 2: Register it in the imports file:</strong></p><pre># src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports<br>com.company.platform.http.CompanyHttpClientAutoConfiguration</pre><p><strong>Step 3: Control ordering, if it matters.</strong> If your auto-configuration needs to run before or after another one (say, you’re customizing the RestClient that another starter also configures), use the ordering annotations rather than guessing at classpath scan order:</p><pre>@AutoConfiguration(after = RestClientAutoConfiguration.class)<br>public class CompanyHttpClientAutoConfiguration {<br>    // your customizations apply after Spring Boot&#39;s own RestClient defaults exist<br>}</pre><p>@AutoConfigureAfter and @AutoConfigureBefore exist as standalone annotations too, for cases where you need to reference multiple classes or can&#39;t use the @AutoConfiguration shorthand. Either way: never rely on alphabetical or classpath order for this. It&#39;s not guaranteed, and it will eventually bite you when a new dependency shifts the scan order.</p><p>Package this as its own module (a shared platform-autoconfigure artifact that every service depends on), and every team in the organization gets consistent HTTP client behavior (retries, tracing headers, timeouts) for free, the same way you get a free RedisTemplate. They can still override it with their own @Bean if they have a real reason to, because @ConditionalOnMissingBean is doing the same backing-off behavior Spring&#39;s own starters use.</p><h3>Debugging: Why Did (or Didn’t) This Bean Get Created?</h3><p>When auto-configuration doesn’t behave the way you expect (a bean you thought would exist doesn’t, or one you didn’t want does), guessing is the wrong approach. Spring Boot can tell you exactly why.</p><p><strong>Option 1: The </strong><strong>--debug flag</strong></p><pre>java -jar myapp.jar --debug</pre><p>This prints a full <strong>Conditions Evaluation Report</strong> at startup: every auto-configuration class Spring Boot considered, split into two lists.</p><pre>=========================<br>CONDITIONS EVALUATION REPORT<br>=========================</pre><pre>Positive matches:<br>-----------------<br>   RedisAutoConfiguration matched:<br>      - @ConditionalOnClass found required class<br>        &#39;org.springframework.data.redis.connection.RedisConnectionFactory&#39;</pre><pre>Negative matches:<br>-----------------<br>   MongoAutoConfiguration:<br>      Did not match:<br>         - @ConditionalOnClass did not find required class<br>           &#39;com.mongodb.client.MongoClient&#39;</pre><p>Every single condition, for every single candidate class, with the exact reason it passed or failed. This is the ground truth: no guessing about why a bean exists or doesn’t.</p><p><strong>Option 2: The Actuator </strong><strong>/actuator/conditions endpoint</strong></p><p>For a running application (or anywhere --debug isn&#39;t convenient: staging, or a container you can&#39;t easily restart), expose the same report over HTTP:</p><pre># application.yml<br>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: conditions</pre><pre>curl localhost:8080/actuator/conditions | jq &#39;.contexts.application.positiveMatches.RedisAutoConfiguration&#39;</pre><p>Same data as the --debug report, queryable without a restart: useful when you&#39;re debugging a production incident and a restart is the last thing you want to do.</p><p><strong>The practical debugging flow:</strong></p><ol><li>Bean you expected isn’t there → check negativeMatches for that auto-configuration class, find the condition that failed, fix the missing dependency/property</li><li>Bean you didn’t expect is there → check positiveMatches, find which starter&#39;s auto-configuration created it, decide whether to exclude it or override it</li><li>Two starters conflict → @ConditionalOnMissingBean means whichever auto-configuration class runs <em>first</em> wins; use @AutoConfiguration(before = ...) on the one you want to win, or exclude the other explicitly:</li></ol><pre>@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })<br>public class MyApplication { }</pre><pre># Or exclude from application.yml, useful when you don&#39;t control the main class<br>spring:<br>  autoconfigure:<br>    exclude:<br>      - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration</pre><h3>The Mental Model, In One Sentence</h3><p>Auto-configuration is not magic, and it is not a priority system. It is a large, flat list of candidate @Configuration classes, filtered down by cheap, composable @Conditional checks (classpath checks first, bean-existence checks second), and the single rule that makes it all predictable is that <strong>your own </strong><strong>@Bean always wins</strong>, because every starter&#39;s auto-configuration is written to back off when it finds one.</p><p>Once that model is in your head, the failure modes stop being mysterious. A missing bean means a condition failed: go read the report. An unwanted bean means a condition passed that you didn’t expect: go read the report. A conflict between two starters means an ordering problem: control it explicitly instead of hoping the classpath scan cooperates.</p><p>You’ve been relying on this mechanism since your first @SpringBootApplication. Now you know what it&#39;s actually doing.</p><p><em>Next in the Spring Boot Essentials 2026 series: </em><strong><em>Spring Boot and Dependency Injection: Beyond the Basics</em></strong><em>, covering bean scopes, circular dependency resolution, </em><em>@Primary vs </em><em>@Qualifier, and the </em><em>ApplicationContext lifecycle.</em></p><h3>Beyond the Code: The Realities of Engineering</h3><p>Knowing how auto-configuration works makes you better at debugging your own systems. It doesn’t teach you how to navigate the conversation when a platform team’s shared auto-configuration module breaks three other teams’ services, and everyone’s looking for who to blame.</p><p>I’ve distilled the unwritten rules of navigating software engineering careers into a practical field guide.</p><p>👉 <a href="https://ankitv2717.gumroad.com/"><strong>Get “Beyond the Offer Letter” on Gumroad here</strong></a> and learn how software companies actually work so you can accelerate your engineering career.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c3faaa8184d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/how-spring-boot-auto-configuration-actually-works-8c3faaa8184d">How Spring Boot Auto-Configuration Actually Works</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot 4: The Big Picture]]></title>
            <link>https://medium.com/javarevisited/spring-boot-4-the-big-picture-bfbd30b905d0?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfbd30b905d0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Mon, 18 May 2026 15:33:02 GMT</pubDate>
            <atom:updated>2026-05-18T15:33:02.088Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Before you read any changelog, you need to understand what Spring Boot 4 actually is, where it came from, and what problem it’s trying to solve in 2026.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xycq7nggG6LfrxX_" /><figcaption>Photo by <a href="https://unsplash.com/@raushanraj?utm_source=medium&amp;utm_medium=referral">Raushan Raj</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to <strong>Spring/SpringBoot Essentials 2026, </strong>a series for Java engineers who want to understand the Spring ecosystem deeply, not just use it.</p><p>This article is the entry point to the series. Not a changelog. Not a migration guide. A map.</p><p>Before you can make sense of what changed in Spring Boot 4, you need to understand what Spring Boot is actually doing under the hood, why the version number jumped from 3 to 4, and what the people who built it are trying to solve for. The rest of the series builds on top of that context.</p><p>Next up: in <strong>Spring Boot Essentials 2026: Everything That Changed from Spring 6 to Spring 7</strong>, we cover BeanRegistrar, JSpecify null safety, native API versioning, modularization, and the full dependency purge. <a href="https://medium.com/illumination/spring-boot-essentials-2026-the-ultimate-guide-to-spring-framework-7-vs-spring-6-9b705f1d5e9c">Read here.</a></p><h3>Start Here: Spring Boot vs. Spring Framework</h3><p>Most developers use Spring Boot without ever clearly separating it from Spring Framework in their mental model. The distinction matters.</p><p><strong>Spring Framework</strong> is the core, the dependency injection container, the bean lifecycle, the AOP infrastructure, the transaction management, the web layer (MVC and WebFlux), the data access abstractions. It’s been around since 2003. It’s the engine.</p><p><strong>Spring Boot</strong> is the configuration layer on top. It adds:</p><ul><li>Auto-configuration: the logic that looks at your classpath and automatically wires up beans so you don’t have to</li><li>Starters: curated, tested dependency bundles (spring-boot-starter-web pulls in Tomcat, Jackson, Spring MVC, correctly versioned together)</li><li>An opinionated default stance: sensible defaults for everything, override only what you need</li><li>Production tooling: health checks, metrics, externalized configuration, graceful shutdown</li></ul><p>The version relationship is direct:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*WbBEAtYJt1uZFfLYpISaug.png" /><figcaption>Spring and its corresponding springBoot Verions</figcaption></figure><p>When you see “Spring Boot 4,” you’re looking at a distribution of Spring Framework 7. Every architectural decision in Framework 7 is surfaced through Boot 4.</p><p>This is why major Boot versions are significant. They’re not just configuration changes, they’re a new version of the engine.</p><h3>Why Spring Boot 4 Exists</h3><p>To understand Boot 4, you need to understand what Boot 3 did and what problem it left unsolved.</p><h3>Boot 3 Was a Forced Modernization</h3><p>Spring Boot 3 (released late 2022) was uncomfortable on purpose.</p><p>It broke things that had worked fine for years:</p><ul><li>It set <strong>Java 17 as the minimum baseline</strong>, forcing teams off Java 8 and 11</li><li>It completed the <strong>javax → </strong><strong>jakarta namespace migration</strong>, which broke every library that hadn&#39;t been updated to Jakarta EE 9</li><li>It introduced <strong>GraalVM Native Image support, </strong>compile your Spring app to a native binary, start in milliseconds, use a fraction of the memory</li></ul><p>Boot 3’s job wasn’t to add exciting features. It was to tear out the old foundation and pour a new one. The javax → jakarta migration alone required rebuilding the import structure of the entire Java EE ecosystem. That was the work.</p><p>Boot 3 paid the migration tax. Boot 4 spends the dividend.</p><h3>Boot 4 Is What That Investment Was For</h3><p>Spring Boot 4 (released late 2025) is built on Spring Framework 7 and Jakarta EE 11. It assumes the new foundation is in place and builds on top of it.</p><p>The pattern repeats: Boot 3 prepared the platform. Boot 4 uses it.</p><p>The specific things Boot 4 is designed to deliver, leaner startup, smaller binaries, cloud-native performance, first-class observability, were architecturally impossible in the Boot 2 era. The jakarta migration, the Java 17 baseline, the AOT infrastructure from Boot 3 were prerequisites.</p><p>Understanding this sequence changes how you think about Boot 4. It’s not a random collection of new features. It’s the payoff of a multi-year strategic direction.</p><h3>What Spring Boot 4 Actually Changes</h3><p>There are four areas where Boot 4 makes a meaningful structural difference. These are not changelog items, they’re shifts in how the framework operates.</p><h3>1. Startup Is No Longer Reflection-Driven</h3><p>The most fundamental change in Boot 4 is invisible in your code. It’s in how Spring builds your application context.</p><p>In Boot 3, startup looked like this:</p><ol><li>Spring scans your classpath</li><li>Reads @Configuration classes through reflection</li><li>Evaluates @Conditional expressions at runtime to decide which beans to create</li><li>Resolves dependencies and builds the full application context</li></ol><p>All of this happens at runtime, every time your application starts. For a medium-sized Spring Boot application, this process alone can take 3-8 seconds.</p><p>Boot 4 introduces a new API which is <strong>BeanRegistrar: </strong>that changes when this work happens:</p><pre>// Boot 3 — reflection-based, evaluated at runtime<br>@Configuration<br>public class PaymentConfig {<br><br>    @Bean<br>    @ConditionalOnProperty(&quot;payment.stripe.enabled&quot;)<br>    public StripeGateway stripeGateway(StripeProperties props) {<br>        return new StripeGateway(props.getApiKey());<br>    }<br>}</pre><pre>// Boot 4 — explicit, evaluated at build time<br>public class PaymentRegistrar implements BeanRegistrar {<br><br>    @Override<br>    public void register(BeanRegistry registry, Environment env) {<br>        if (env.getProperty(&quot;payment.stripe.enabled&quot;, Boolean.class, false)) {<br>            registry.registerBean(&quot;stripeGateway&quot;, StripeGateway.class,<br>                spec -&gt; spec.supplier(ctx -&gt;<br>                    new StripeGateway(ctx.getBean(StripeProperties.class).getApiKey())<br>                )<br>            );<br>        }<br>    }<br>}</pre><p>The difference: the @Bean / @Configuration approach requires Spring to interrogate your bytecode at runtime. The BeanRegistrar approach is explicit, Spring doesn&#39;t need to infer anything. The AOT compiler can process it at build time.</p><p>For a containerized microservice, this is the difference between a 5-second cold start and a sub-second one. In a Kubernetes environment where pods are scaled and replaced continuously, that gap compounds.</p><p>You don’t have to migrate to BeanRegistrar immediately, Boot 4 still supports @Configuration. But new code and new projects should prefer the explicit approach.</p><h3>2. The Dependency Footprint Got Smaller</h3><p>Boot 3 had a monolithic auto-configuration jar: spring-boot-autoconfigure. It contained the auto-configuration logic for databases, message queues, web servers, caches, observability, all of it, in one artifact. Even if your application only needed database auto-configuration, you dragged in the entire jar.</p><p>Boot 4 splits this into <strong>over 70 focused modules</strong>:</p><pre>spring-boot-autoconfigure-jdbc<br>spring-boot-autoconfigure-kafka<br>spring-boot-autoconfigure-redis<br>spring-boot-autoconfigure-web-servlet<br>spring-boot-autoconfigure-actuator<br>... (70+ total)</pre><p>You only get the auto-configuration for what you actually declare as a dependency.</p><p>This matters for two reasons:</p><p><strong>GraalVM native compilation.</strong> The AOT compiler has to process every @ConditionalOnClass it can find. With a smaller classpath, it does less work, produces smaller binaries, and produces them faster.</p><p><strong>Startup classpath scanning.</strong> Less code on the classpath means Spring has less to evaluate at startup, even in JVM mode, not just native.</p><p>For most developers, this change is completely transparent. Your spring-boot-starter-web dependency still works the same way. What changes is what&#39;s pulled in transitively, and how lean the resulting artifact is.</p><h3>3. Resilience Is Now Built In</h3><p>Microservices fail. Not sometimes, routinely. External APIs return 503. Database connections time out. Message brokers restart.</p><p>Boot 3 had no native answer to this. You reached for Resilience4j, Spring Cloud Circuit Breaker, or Bucket4j. Three different libraries, three different configuration models, three different health indicator integrations.</p><p>Boot 4 brings two resilience primitives directly into the core framework:</p><pre>// Automatic retry with exponential backoff — no Resilience4j needed<br>@Service<br>public class InventoryService {<br><br>    @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 200, multiplier = 2.0))<br>    public InventoryStatus checkStock(String productId) {<br>        return warehouseClient.getStock(productId); // external HTTP call<br>    }<br><br>    @Recover<br>    public InventoryStatus fallback(Exception ex, String productId) {<br>        log.warn(&quot;Warehouse unavailable for {}, returning cached status&quot;, productId);<br>        return inventoryCache.getLast(productId);<br>    }<br>}</pre><pre>// Concurrency limiting — prevent a slow endpoint from overwhelming your thread budget<br>@Service<br>public class ReportService {<br><br>    @ConcurrencyLimit(value = 5) // max 5 concurrent report generations<br>    public Report generateAnnualReport(String tenantId) {<br>        // CPU-intensive, long-running work<br>        return reportEngine.buildAnnual(tenantId);<br>    }<br>}</pre><p>Both annotations are AOP-based, Spring wraps the method call. Crucially, they preserve the calling thread’s security context, trace context, and Scoped Values. This was the persistent problem with external resilience libraries: their retry threads didn’t carry the caller’s context, breaking distributed tracing and security propagation.</p><p>The built-in implementation doesn’t have this problem because it never leaves Spring’s context machinery.</p><h3>4. Observability Got Native</h3><p>Observability in Boot 3 was a configuration exercise. Micrometer was the abstraction layer. Tracing required wiring up a Brave or OpenTelemetry bridge. Getting trace IDs to propagate correctly through @Async methods, RestTemplate calls, and reactive chains was a non-trivial integration task.</p><p>Boot 4 changes the default:</p><pre># application.yml — Boot 3 (manual OTel setup required)<br>management:<br>  tracing:<br>    sampling:<br>      probability: 1.0<br>  zipkin:<br>    tracing:<br>      endpoint: http://zipkin:9411/api/v2/spans<br><br># Also needed: manual OTel SDK configuration, tracer bean setup, exporter config...</pre><pre># application.yml — Boot 4 (native OTLP out of the box)<br>management:<br>  otlp:<br>    tracing:<br>      endpoint: http://otel-collector:4318/v1/traces<br>    metrics:<br>      export:<br>        url: http://otel-collector:4318/v1/metrics</pre><h3>What Boot 4 Requires From You</h3><p>Boot 4 isn’t free. It raises the floor.</p><p><strong>Java 21 is the new minimum.</strong> Java 17 runs it technically, but you won’t get Virtual Threads (first-class in Boot 4), Scoped Values, or Project Leyden startup optimizations without Java 21+. In practice, Java 21 is the real baseline. Java 25 is the recommended production target in 2026.</p><p><strong>Jakarta EE 11.</strong> The javax → jakarta migration that Boot 3 introduced is table stakes now. If your third-party libraries haven&#39;t made that transition, they don&#39;t work with Boot 4. This is the most common hidden breakage in the ecosystem.</p><p><strong>Undertow is gone.</strong> It doesn’t support Servlet 6.1, which is required by Jakarta EE 11. If you’re using Undertow as your embedded server, you need to switch to Tomcat 11+ or Jetty 12.1+ before upgrading.</p><p><strong>Jackson 3.</strong> Boot 4 ships Jackson 3, which changes package names (com.fasterxml.jackson.* → tools.jackson.*) and the exception hierarchy. Custom serializers and ObjectMapper beans need updating.</p><p><strong>JUnit 4 is removed.</strong> The junit-vintage-engine bridge is gone. JUnit 4 tests won&#39;t run — not with an error, just silently. Migration to JUnit 5 (Jupiter) is required.</p><p>None of these are arbitrary. Each removal is explained by a technical constraint: Undertow couldn’t support Jakarta EE 11, Jackson 2 had reached API design limits, JUnit 4 had been superseded for years. The Spring team isn’t making changes for the sake of it.</p><h3>The Technology Stack in 2026</h3><p>Here’s the complete picture of what Boot 4 runs on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*h_tk_ryLCMakPYjiC21S7g.png" /><figcaption>Technology Stack for the new SpringBoot Version</figcaption></figure><p>This is not a list of updates. It’s a coherent platform, every layer aligned to the same Java version, the same Jakarta namespace, the same observability standard.</p><h3>Should You Start With Boot 4 or Boot 3?</h3><p><strong>Starting a new project in 2026:</strong> Start with Boot 4. There’s no technical reason to start on Boot 3 today. The platform is stable, the ecosystem has caught up, and you’ll be building on the right foundation from day one.</p><p><strong>Running a Boot 3 application:</strong> You don’t need to migrate immediately. Boot 3 is still maintained. Migrate when you have a concrete reason, a major feature needing Virtual Threads, a performance goal that requires the leaner startup, or a migration cycle already underway.</p><p><strong>Running a Boot 2 application:</strong> This is where urgency applies. Boot 2’s Spring Framework 5.x baseline is no longer receiving security patches. The path is Boot 2 → Boot 3.5.x (clearing all deprecations) → Boot 4. Don’t skip the middle step.</p><p>The migration guide (Article 3 in this series) covers every breaking change and the exact code to fix each one.</p><h3>The Direction of Travel</h3><p>There’s a thread connecting everything in Boot 4, startup time, binary size, native compilation, cloud-native performance.</p><p>Spring Boot was born in an era of monolithic deployments. An application started once and ran for weeks. Startup time of 30 seconds was acceptable. Memory usage in the gigabytes was fine.</p><p>The deployment model changed. Kubernetes schedules and reschedules pods constantly. Serverless functions start on demand. Edge deployments run on constrained hardware. In these environments, a slow-starting, memory-heavy JVM application is a real operational problem.</p><p>Boot 3 laid the groundwork: Jakarta EE namespace, Java 17 baseline, GraalVM AOT infrastructure.</p><p>Boot 4 delivers on it: sub-second startup potential through BeanRegistrar and AOT repositories, lean dependency graph through modularization, minimal-reflection context construction.</p><p>The Spring team is not building for the enterprise server rooms of 2015. They’re building for a deployment model where applications start in milliseconds, scale down to zero, and run efficiently in containers on the edge.</p><p>If you understand that, every decision in Boot 4 makes sense.</p><h3>Beyond the Code: The Realities of Engineering</h3><p>Knowing what Spring Boot 4 is gives you technical depth. Making the case to your team for a major framework upgrade, framing the risk, getting alignment, owning the outcome, requires a completely different skill set.</p><p>I’ve distilled the unwritten rules of navigating decisions like these inside software companies into a practical field guide.</p><p>👉 <a href="https://ankitv2717.gumroad.com/"><strong>Get “Beyond the Offer Letter” on Gumroad here</strong></a><strong>: </strong>and learn how software companies actually work so you can accelerate your engineering career.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfbd30b905d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-boot-4-the-big-picture-bfbd30b905d0">Spring Boot 4: The Big Picture</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I’m Building an Open-Source Runtime Memory Simulator, And I Want Your Input]]></title>
            <link>https://blog.stackademic.com/im-building-an-open-source-runtime-memory-simulator-and-i-want-your-input-88c6b59e1572?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/88c6b59e1572</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Mon, 18 May 2026 08:43:13 GMT</pubDate>
            <atom:updated>2026-05-18T08:43:13.915Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A visual, interactive tool for understanding how garbage collectors and memory managers actually behave, across JVM and Node.js.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vh9SQ4JF-aj-FBSk" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here’s something I’ve noticed after years of backend engineering.</p><p>Most developers, including experienced ones, have a vague, approximate understanding of how garbage collection works.</p><p>They know it “frees memory.” They know it “causes pauses.” They’ve seen the GC logs, maybe tuned a flag or two in production. But ask them what actually happens inside the JVM when G1 GC fires a mixed collection, or why ZGC can collect concurrently while your application threads keep running, or how Generational ZGC in Java 21 is fundamentally different from the original ZGC in Java 17, and most engineers go quiet.</p><p>That knowledge gap has real consequences. GC-related issues are some of the hardest production problems to diagnose precisely because most engineers can’t visualize what’s happening.</p><p>That’s what I’m trying to fix.</p><h3>What I’m Building</h3><p>I’m building an <strong>open-source, visual, interactive runtime memory simulator, </strong>a tool that lets you watch garbage collectors and memory managers work in real time, side by side, at your own pace.</p><p>The project is called <strong>JVM GC Algorithms</strong> and it’s currently live on GitHub.</p><p>The current version is a Java/Spring Boot backend with an Angular frontend. It simulates <strong>10 garbage collection algorithms</strong> across Java 8, Java 17, and Java 21:</p><p><strong>Java 8 era:</strong></p><ul><li>Serial GC</li><li>Parallel GC</li><li>CMS (Concurrent Mark Sweep)</li><li>G1 GC</li></ul><p><strong>Java 17 era:</strong></p><ul><li>Enhanced G1 GC</li><li>ZGC</li><li>Shenandoah GC</li></ul><p><strong>Java 21 era:</strong></p><ul><li>Latest G1 GC</li><li>Generational ZGC</li><li>Generational Shenandoah</li></ul><p>For each algorithm, you can:</p><ul><li><strong>Allocate objects</strong> manually (50 at a time) or let the simulator run automatically</li><li><strong>Watch live memory bars</strong> for Eden, Survivor-0, Survivor-1, Old Generation, and Metaspace fill up in real time</li><li><strong>Trigger GC manually</strong> and observe exactly what happens, which regions are collected, what’s promoted, what pause time occurs</li><li><strong>Compare pause times</strong> across algorithms as you switch between them</li><li><strong>Read the GC event log</strong> which describes what happened at each collection cycle</li></ul><p>The goal is not just to show that ZGC is faster than Serial GC. It’s to let you <em>see</em> why. To watch the difference between a stop-the-world pause and a concurrent collection. To understand what “Eden is full” actually means for allocation performance.</p><h3>Why I Built This</h3><p>I’ve been writing about the JVM on Medium for a while now, Virtual Threads, Project Loom, Java 25, the whole generational GC evolution. And the feedback I consistently get is some version of:</p><blockquote>“I understand the words. I just can’t picture it.”</blockquote><p>Reading about garbage collection is one thing. Watching it happen, allocating objects, seeing Eden fill up, watching the GC kick in and reclaim space, observing the pause time, is something completely different.</p><p>A lot of GC tutorials show static diagrams. Heap regions with arrows. Before/after states. These are fine for introducing concepts, but they don’t show the <em>dynamic</em> nature of memory management, the continuous cycle of allocation, collection, promotion, and compaction that runs throughout your application’s entire lifetime.</p><p>I wanted to build something you could interact with, not just read.</p><h3>What’s Coming Next, Node.js Runtime</h3><p>Here’s where I’d love your feedback most.</p><p>The JVM GC simulator is the first runtime. The next one I’m planning to add is <strong>Node.js, </strong>and this is where it gets more interesting.</p><p>Node.js uses the <strong>V8 garbage collector</strong>, which is completely different in design from JVM collectors. V8 is generational (young space / old space), uses a scavenger algorithm for young generation collection, and has a mark-compact collector for old generation. It also has a completely different memory ceiling, V8’s default heap is limited to around 1.5GB on 64-bit systems, which is a real constraint Node.js developers hit in production.</p><p>Adding Node.js would mean:</p><ul><li>Simulating V8’s <strong>young space (Scavenge)</strong> vs <strong>JVM’s Eden + Minor GC</strong></li><li>Visualizing V8’s <strong>old space (Mark-Compact)</strong> vs <strong>JVM’s Old Generation (Major/Full GC)</strong></li><li>Showing the fundamental difference between the JVM’s mature, tunable GC ecosystem and V8’s streamlined but constrained model</li><li>Side-by-side comparisons, what does handling the same allocation pattern look like in the JVM vs V8?</li></ul><p>The idea is to make this a <strong>cross-runtime memory education tool</strong>, not just a JVM-specific one.</p><h3>What I Want to Know From You</h3><p>This is genuinely early-stage planning. Before I build further, I want feedback from the people who would actually use this.</p><p><strong>A few specific questions:</strong></p><p><strong>1. What would make this useful to you as a learning tool?</strong> Is the current simulation-based approach the right format? Would you rather have guided walkthroughs explaining what you’re seeing, or do you prefer exploring freely?</p><p><strong>2. What other runtimes or scenarios matter to you?</strong> Node.js V8 is my next target. But would Python’s memory model (reference counting + cyclic GC) be useful? Go’s tri-color mark-and-sweep? Are there specific JVM collectors you’d want to see compared: for example, ZGC vs Shenandoah vs G1 for the same allocation workload?</p><p><strong>3. What do you find hardest to understand about GC right now?</strong> Is it the algorithm differences? The tuning flags? When to use which collector? Understanding what GC logs are telling you? Knowing what’s happening when your production app pauses unexpectedly?</p><p><strong>4. What features are missing that you’d want?</strong> A few ideas I’m considering:</p><ul><li><strong>Benchmark mode: </strong>run the same workload across multiple algorithms and show a comparison table of pause times, throughput, and memory efficiency</li><li><strong>Preset scenarios: </strong>“simulate a high-allocation microservice,” “simulate a batch job,” “simulate a long-running background process”</li><li><strong>GC log importer: </strong>paste your actual production GC logs and visualize them in the same interface</li><li><strong>Memory leak simulation: </strong>watch what happens to Old Gen when objects are never released</li></ul><p>Are any of these compelling? Are there things not on this list that would make this genuinely useful in your day-to-day work?</p><h3>The GitHub Repo</h3><p>The project is open source and the current version is live:</p><p><strong>→ </strong><a href="https://github.com/ankitverma2717/JVM-GC-Collection-Algorithms"><strong>github.com/ankitverma2717/JVM-GC-Collection-Algorithms</strong></a></p><p>It runs with a single Gradle command, no installation required. If you want to try it, clone it, run ./gradlew run, and see how far you get before something confuses you. That confusion is useful feedback too.</p><h3>Why This Matters Beyond the Tool</h3><p>There’s a broader point I want to make.</p><p>The engineers who understand GC at a deeper level are the ones who can:</p><ul><li>Look at a production GC log and tell you exactly why the application slowed down at 3am</li><li>Tune -XX:MaxGCPauseMillis with confidence instead of guessing</li><li>Explain to a non-technical stakeholder why “adding more heap” won’t fix the problem</li><li>Make a real argument for switching from G1 to ZGC in a latency-sensitive service</li></ul><p>That knowledge gap between “I’ve heard of garbage collection” and “I understand how my runtime manages memory” is where a lot of production incidents live.</p><p>A tool that closes that gap, even partially, is worth building.</p><h3>Leave Your Feedback</h3><p>I read every response. If you have thoughts, about the existing simulator, about the Node.js addition, about features you’d want, or about GC concepts you’ve always found confusing, leave a comment below.</p><p>This is the kind of project that gets better with input from people who actually work with these systems. I’d rather know what you need before I build it than after.</p><p>Also You can also email me at ankit.dev273@gmail.com<br>or send me a DM with your feedback on <a href="https://www.linkedin.com/in/ankit2717/">Linkedin</a>. I would also be happy to connect with you there!</p><p><em>If you’re new here: I write about Java, the JVM, backend systems, and distributed architecture. The GC simulator is part of a broader effort to make complex systems concepts visual and interactive. Follow along if that’s useful to you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88c6b59e1572" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/im-building-an-open-source-runtime-memory-simulator-and-i-want-your-input-88c6b59e1572">I’m Building an Open-Source Runtime Memory Simulator, And I Want Your Input</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot 4 Migration Guide: What Breaks and How to Fix It]]></title>
            <link>https://medium.com/javarevisited/spring-boot-4-migration-guide-what-breaks-and-how-to-fix-it-60373ca4683e?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/60373ca4683e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Sat, 16 May 2026 10:42:32 GMT</pubDate>
            <atom:updated>2026-05-18T04:59:26.224Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Spring Boot 4 was released in November 2025. It’s a major upgrade. Here’s exactly what will break in your application, and the precise steps to fix each issue.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mvgm8keu5fzoFXSC" /><figcaption>Photo by <a href="https://unsplash.com/@barbarazandoval?utm_source=medium&amp;utm_medium=referral">Barbara Zandoval</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is Article 3 in the Spring Boot Essentials 2026 series. In Article 2, <strong>Spring Boot Essentials 2026: Everything That Changed from Spring 6 to Spring 7</strong>, we covered BeanRegistrar, JSpecify null safety, native API versioning, modularization into 70+ granular modules, and the full dependency purge. <a href="https://medium.com/illumination/spring-boot-essentials-2026-the-ultimate-guide-to-spring-framework-7-vs-spring-6-9b705f1d5e9c">Read here.</a></p><p>Up next in Article 4, <strong>Virtual Threads in Spring Boot 4: What Actually Changes for Your Code</strong>, we cover what enabling virtual threads actually does to your application, connection pool recalibration, the synchronized pinning problem, ThreadLocal at scale, and whether you still need WebFlux. <a href="https://medium.com/javarevisited/virtual-threads-in-spring-boot-4-what-actually-changes-for-your-code-9b490b57f400">Read here.</a></p><p>Let’s be direct about what kind of article this is.</p><p>This is not a list of exciting new features. It’s not a “what’s new in Spring Boot 4” post. There are plenty of those.</p><p>This is the article you need when you’re staring at a build that was working fine on Spring Boot 3, and now it isn’t. Or when your tech lead just announced that the team is migrating, and you need to know exactly what’s going to break before you write a single line of migration code.</p><p>Spring Boot 4 built on Spring Framework 7 and Jakarta EE 11, is the most disruptive Spring release since the javax → jakarta namespace change in Spring 6. It raised the Java baseline, dropped Undertow, ripped out JUnit 4, upgraded Jackson to a breaking major version, and changed Spring Security defaults that silently break REST APIs.</p><p>Most of these breaks produce no obvious error message. They just make your application behave wrong.</p><p>This guide covers each breaking category with: what broke, why it broke, and the exact code to fix it.</p><h3>Before You Touch Your POM: The Migration Strategy</h3><p>One rule applies above everything else:</p><p><strong>Never jump directly from Spring Boot 2.x or 3.x to Spring Boot 4 in a single commit.</strong></p><p>The migration path is a two-phase staircase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*vFyc3Td5OFb40VGIQwdeaA.png" /></figure><p><strong>Why this matters:</strong> Every API deprecated in the 3.x lifecycle is <em>removed</em> in 4.0, not soft-deprecated, not conditionally available. Gone. If you skip the intermediate step, you’re fighting removal errors and unfamiliar APIs at the same time. That’s how migrations take months instead of weeks.</p><p>The process on the 3.5.x intermediate step:</p><ol><li>Upgrade to Spring Boot 3.5.x (latest patch)</li><li>Add the properties migrator, it will list every property that has changed</li><li>Run your test suite and treat every deprecation warning as a migration task, not a warning</li><li>Clear all deprecations completely before incrementing to 4.0</li></ol><p>Only then open the POM and change 3.5.x to 4.0.0.</p><h3>Break #1: Java 21 Is Now the Minimum</h3><p><strong>What breaks:</strong> Your CI/CD pipeline, your Docker base images, and your local dev setup, if any of them are running Java 17.</p><p>Spring Boot 4 requires <strong>Java 21 as the minimum baseline</strong>. The primary driver is Jakarta EE 11, which draws on APIs that require Java 21. Virtual Threads, which Spring Boot 4 has first-class support for, are also a Java 21 feature.</p><p><strong>How to fix it:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*eexvxahevexGQI3LFvf_Dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*xKniH9b-Pp8r3IWWrULbBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*ibvzYWEz2IohlPxhnsB9Kw.png" /></figure><p><strong>If you’re still on Java 17 infrastructure:</strong> Spring Boot 4 will technically run, because the Java baseline is 21, not 25. But you won’t have access to Virtual Threads, Scoped Values, or any of the Project Leyden startup optimizations. And Jakarta EE 11 features depend on Java 21 APIs. Upgrade to at least Java 21 before migrating to Spring Boot 4. Java 25 is the recommended production target in 2026.</p><h3>Break #2: Undertow Is Gone</h3><p><strong>What breaks:</strong> Any application using spring-boot-starter-undertow will fail to start. Not with a graceful error, with a hard ClassNotFoundException because the Undertow autoconfiguration module no longer exists.</p><p>Undertow was dropped because it does not support <strong>Servlet 6.1</strong>, which is required by Jakarta EE 11. Spring Boot 4 made no exceptions.</p><p><strong>How to fix it:</strong></p><p>Switch to Tomcat (the default) or Jetty before upgrading. Do this while you’re still on Spring Boot 3.5.x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*GmNFjmScGjii_-BdmBb8aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*Q7xs4RNFOFDl70RP8dm8rA.png" /></figure><p>If you had Undertow-specific configuration properties (thread counts, buffer sizes), they don’t map 1:1 to Tomcat. Run the properties migrator (covered below) and audit your application.properties after switching.</p><h3>Break #3: Spring Security: The Silent 403</h3><p>This is the break that hurts the most, because it doesn’t crash your application. It just makes your API silently return 403 Forbidden for every POST, PUT, DELETE, and PATCH request.</p><p><strong>What changed:</strong> Spring Security 7 (bundled with Spring Boot 4) changed CSRF protection defaults to be more aggressively enforced. REST APIs that were previously working without an explicit SecurityFilterChain bean, relying on Spring&#39;s auto-configuration to be permissive, will now block all state-changing requests.</p><p>Additionally, WebSecurityConfigurerAdapter , deprecated in Spring Security 5.7, is <strong>completely removed in Spring Security 7</strong>. If you&#39;re still extending it, your application won&#39;t compile.</p><p><strong>Fix 1: Remove </strong><strong>WebSecurityConfigurerAdapter entirely</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*aQ0c1IGpTGE3xsKM0b-DCw.png" /></figure><p>Note: authorizeRequests() → authorizeHttpRequests(). antMatchers() → requestMatchers(). Both old APIs are removed in Spring Security 7.</p><p><strong>Fix 2: Handle CSRF for stateless REST APIs</strong></p><p>If your API uses JWT or OAuth2 bearer tokens and is completely stateless (no session cookies), CSRF protection is not needed, and must be explicitly disabled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*F_d9kNeyn_gbc8D3FZi-bw.png" /></figure><p><strong>Fix 3: Handle CSRF for session-based authentication (traditional web apps)</strong></p><p>If your application uses session cookies for authentication (form login, traditional Spring MVC apps), you need CSRF, but it must be explicitly configured for your frontend to read it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*YCoDikrmEAEMzAUAuVOvZg.png" /></figure><p><strong>The rule:</strong> In Spring Security 7, there is no implicit behavior. Every security behavior must be explicitly declared. If something isn’t working, add logging:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*7BgRaT5Q7Z5aQxur4o5vRA.png" /></figure><p>Look for &quot;FilterSecurityInterceptor&quot; and &quot;CSRF&quot; entries. The 403 source is almost always visible there.</p><h3>Break #4: Jackson 3: Custom Serializers Stop Working</h3><p><strong>What breaks:</strong> Any class that extends JsonSerializer&lt;T&gt;, JsonDeserializer&lt;T&gt;, or StdSerializer&lt;T&gt; with Jackson 2.x APIs. Any direct use of ObjectMapper constructors. Any class registered via @JsonComponent.</p><p>Spring Boot 4 ships with <strong>Jackson 3</strong> as the default JSON library. Jackson 3 is a major version with API-level breaking changes, it’s not a drop-in replacement.</p><p><strong>Break 1: </strong><strong>ObjectMapper construction</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*zfDzrCFtUtQDdQnGfeAIGg.png" /></figure><p><strong>Break 2: Custom serializers</strong></p><pre>// BEFORE — Jackson 2 custom serializer<br>import com.fasterxml.jackson.databind.ser.std.StdSerializer;<br>import com.fasterxml.jackson.core.JsonGenerator;<br>import com.fasterxml.jackson.databind.SerializerProvider;<br><br>@Component<br>public class MoneySerializer extends StdSerializer&lt;Money&gt; {<br><br>    public MoneySerializer() {<br>        super(Money.class);<br>    }<br><br>    @Override<br>    public void serialize(Money value, JsonGenerator gen, SerializerProvider provider)<br>            throws IOException {<br>        gen.writeStartObject();<br>        gen.writeNumberField(&quot;amount&quot;, value.getAmount());<br>        gen.writeStringField(&quot;currency&quot;, value.getCurrency().getCode());<br>        gen.writeEndObject();<br>    }<br>}<br><br>// AFTER — Jackson 3 (same structure, but updated imports and module registration)<br>import tools.jackson.databind.ser.std.StdSerializer;<br>import tools.jackson.core.JsonGenerator;<br>import tools.jackson.databind.SerializationContext;  // renamed from SerializerProvider<br><br>@Component<br>public class MoneySerializer extends StdSerializer&lt;Money&gt; {<br><br>    public MoneySerializer() {<br>        super(Money.class);<br>    }<br><br>    @Override<br>    public void serialize(Money value, JsonGenerator gen, SerializationContext ctxt)<br>            throws JacksonException {  // IOException → JacksonException<br>        gen.writeStartObject();<br>        gen.writeNumberField(&quot;amount&quot;, value.getAmount());<br>        gen.writeStringField(&quot;currency&quot;, value.getCurrency().getCode());<br>        gen.writeEndObject();<br>    }<br>}</pre><p><strong>Key Jackson 3 API changes to know:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*CbZJr3x_4JAoXlxxUyUexw.png" /></figure><p><strong>The search command to find everything you need to update:</strong></p><pre># Find all files still using Jackson 2 package paths<br>grep -r &quot;com.fasterxml.jackson&quot; src/main/java --include=&quot;*.java&quot; -l<br>grep -r &quot;com.fasterxml.jackson&quot; src/test/java --include=&quot;*.java&quot; -l</pre><p>If the output is long, prioritize: custom serializers/deserializers first, then ObjectMapper beans, then @JsonComponent classes.</p><h3>Break #5: Hibernate 7 : The Database Layer</h3><p><strong>What breaks:</strong> Deprecated Hibernate Session methods that were removed, the renamed annotation processor dependency, and stricter temporal type handling.</p><p>Spring Boot 4 ships with <strong>Hibernate ORM 7.1</strong> and <strong>Jakarta Persistence 3.2</strong>. Most JPQL queries survive unchanged, but specific Hibernate Session API usage will fail at compile time.</p><p><strong>Break 1: Removed </strong><strong>Session methods</strong></p><p>Hibernate 7 removed the legacy Session API methods that were deprecated in Hibernate 6. These were the non-JPA-standard methods that Hibernate added decades ago:</p><pre>// BEFORE — Hibernate 6 / Spring Boot 3 (deprecated but worked)<br>@Repository<br>public class UserRepository {<br><br>    @PersistenceContext<br>    private EntityManager em;<br><br>    public void saveUser(User user) {<br>        Session session = em.unwrap(Session.class);<br>        session.save(user);       // REMOVED in Hibernate 7<br>        session.update(user);     // REMOVED in Hibernate 7<br>        session.saveOrUpdate(user); // REMOVED in Hibernate 7<br>        session.delete(user);     // REMOVED in Hibernate 7<br>    }<br>}<br><br>// AFTER — Hibernate 7 / Spring Boot 4 (JPA standard)<br>@Repository<br>public class UserRepository {<br><br>    @PersistenceContext<br>    private EntityManager em;<br><br>    public void saveUser(User user) {<br>        em.persist(user);     // was: save()<br>        em.merge(user);       // was: update() / saveOrUpdate()<br>        em.remove(user);      // was: delete()<br>    }<br>}</pre><p><strong>Break 2: Annotation processor dependency renamed</strong></p><p>If you use the JPA Static Metamodel Generator (for type-safe Criteria API queries), the artifact ID changed:</p><pre>&lt;!-- BEFORE — Spring Boot 3 / Hibernate 6 --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;<br>    &lt;artifactId&gt;hibernate-jpamodelgen&lt;/artifactId&gt;<br>    &lt;scope&gt;provided&lt;/scope&gt;<br>&lt;/dependency&gt;<br><br>&lt;!-- AFTER — Spring Boot 4 / Hibernate 7 --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.hibernate.orm&lt;/groupId&gt;<br>    &lt;artifactId&gt;hibernate-processor&lt;/artifactId&gt;<br>    &lt;scope&gt;provided&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p><strong>Break 3: Stricter temporal type handling</strong></p><p>Hibernate 7 enforces stricter alignment between Java temporal types and database column types. Instant and OffsetDateTime fields that previously worked without explicit column definitions may now throw schema validation errors.</p><pre>// BEFORE — Spring Boot 3, this worked without column type specification<br>@Entity<br>public class AuditLog {<br>    @Column<br>    private Instant createdAt;   // could silently map to various DB types<br>}<br><br>// AFTER — Spring Boot 4, be explicit about temporal mapping<br>@Entity<br>public class AuditLog {<br><br>    @Column(columnDefinition = &quot;TIMESTAMP WITH TIME ZONE&quot;)<br>    private Instant createdAt;<br><br>    // Or use the JPA 3.2 standard annotation<br>    @Temporal(TemporalType.TIMESTAMP)<br>    @Column<br>    private Instant createdAt;<br>}</pre><p><strong>How to catch schema issues before production:</strong></p><p>Add this to your staging/test profile to run schema validation at startup:</p><pre># application-staging.yml<br>spring:<br>  jpa:<br>    hibernate:<br>      ddl-auto: validate   # Fail fast if schema doesn&#39;t match entities</pre><p>This turns potential silent data corruption issues into hard startup failures, which is exactly what you want during migration testing.</p><h3>Break #6: JUnit 4 Is Gone</h3><p><strong>What breaks:</strong> Every test class using @RunWith, @Rule, @ClassRule, JUnit 4 Assert, or any JUnit 4 runner. This includes Spring&#39;s own @RunWith(SpringRunner.class).</p><p>Spring Boot 4 removed junit-vintage-engine , the bridge that allowed JUnit 4 tests to run inside the JUnit 5 platform. If you have any JUnit 4 tests, they will simply not run, no error, no output, they are invisible to the test runner.</p><p><strong>The migration pattern:</strong></p><pre>// BEFORE — JUnit 4<br>import org.junit.Test;<br>import org.junit.Before;<br>import org.junit.runner.RunWith;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.test.context.junit4.SpringRunner;<br>import static org.junit.Assert.*;<br><br>@RunWith(SpringRunner.class)        // JUnit 4 runner<br>@SpringBootTest<br>public class UserServiceTest {<br><br>    @Before<br>    public void setUp() {<br>        // setup<br>    }<br><br>    @Test<br>    public void testCreateUser() {<br>        User user = userService.create(&quot;alice&quot;);<br>        assertNotNull(user);               // JUnit 4 Assert<br>        assertEquals(&quot;alice&quot;, user.name());<br>    }<br>}<br><br>// AFTER — JUnit 5 (Jupiter)<br>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.BeforeEach;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import static org.junit.jupiter.api.Assertions.*;<br><br>@SpringBootTest             // No @RunWith needed — JUnit 5 uses @ExtendWith internally<br>public class UserServiceTest {<br><br>    @BeforeEach             // was @Before<br>    public void setUp() {<br>        // setup<br>    }<br><br>    @Test<br>    public void testCreateUser() {<br>        User user = userService.create(&quot;alice&quot;);<br>        assertNotNull(user);                     // same method, different import<br>        assertEquals(&quot;alice&quot;, user.name());<br>    }<br>}</pre><p><strong>Full JUnit 4 → JUnit 5 annotation mapping:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*cEA6CXDlxfJfnDL_ylW5Mg.png" /></figure><p><strong>The command to find all JUnit 4 tests:</strong></p><pre>grep -r &quot;org.junit.Test\|org.junit.Before\|RunWith\|SpringRunner&quot; \<br>     src/test/java --include=&quot;*.java&quot; -l</pre><p>Every file in that output needs migration.</p><h3>Break #7: Configuration Properties: Use the Migrator</h3><p>Spring Boot 4 renames and removes dozens of configuration properties. Hunting these manually is error-prone. Use the official tool:</p><p><strong>Step 1: Add the properties migrator as a runtime dependency (temporarily)</strong></p><pre>&lt;!-- pom.xml — add this during migration only --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-properties-migrator&lt;/artifactId&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><pre>// build.gradle<br>runtimeOnly(&quot;org.springframework.boot:spring-boot-properties-migrator&quot;)</pre><p><strong>Step 2: Start your application and read the output</strong></p><p>The migrator prints a startup report like this:</p><pre>WARN : spring-boot-properties-migrator - The following properties are deprecated:<br><br>  spring.redis.host -&gt; spring.data.redis.host<br>  spring.datasource.hikari.maxLifetime -&gt; spring.datasource.hikari.max-lifetime<br>  management.metrics.export.prometheus.enabled -&gt; management.prometheus.metrics.export.enabled<br>  server.undertow.threads.io -&gt; [REMOVED — Undertow is not available]<br><br>Please refer to the migration guide for instructions on how to update your configuration.</pre><p><strong>Step 3: Update your </strong><strong>application.properties / </strong><strong>application.yml</strong></p><p>Fix every property the migrator identified.</p><p><strong>Step 4: Remove the migrator dependency</strong></p><pre>&lt;!-- Remove this before committing the migration --&gt;<br>&lt;!-- spring-boot-properties-migrator should NOT be in production --&gt;</pre><p>Leaving the migrator in production adds startup overhead and may hide future property issues.</p><h3>Break #8: Null Safety: JSpecify Replaces Spring Annotations</h3><p><strong>What breaks:</strong> Kotlin projects in particular. Any code using org.springframework.lang.@Nullable or org.springframework.lang.@NonNull to interact with Spring APIs.</p><p>Spring Boot 4 adopted <strong>JSpecify</strong> (org.jspecify.annotations) as the standard for null-safety annotations across the entire Spring Framework codebase. Spring&#39;s own @Nullable and @NonNull from org.springframework.lang are removed from the framework&#39;s public API surface.</p><p><strong>How to fix it:</strong></p><pre>&lt;!-- Add JSpecify dependency --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.jspecify&lt;/groupId&gt;<br>    &lt;artifactId&gt;jspecify&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>// BEFORE — Spring 6 / Spring Boot 3<br>import org.springframework.lang.Nullable;<br>import org.springframework.lang.NonNull;<br><br>public interface UserRepository {<br>    @Nullable<br>    User findByEmail(@NonNull String email);<br>}<br><br>// AFTER — Spring Boot 4<br>import org.jspecify.annotations.Nullable;<br>import org.jspecify.annotations.NonNull;<br><br>public interface UserRepository {<br>    @Nullable<br>    User findByEmail(@NonNull String email);<br>}</pre><p>The annotation names are identical, only the import package changes. In IntelliJ IDEA, a project-wide find-and-replace on the import path handles this in under a minute:</p><pre>Find:    import org.springframework.lang.Nullable;<br>Replace: import org.jspecify.annotations.Nullable;<br><br>Find:    import org.springframework.lang.NonNull;<br>Replace: import org.jspecify.annotations.NonNull;</pre><p>For Kotlin projects, this change is more impactful. JSpecify is recognized by the Kotlin compiler (K2 and later), which means previously-suppressed null-safety warnings may now surface as compilation errors. Treat them as real issues to fix, not noise to suppress.</p><h3>The Full Migration Checklist</h3><p>Use this as your team’s working checklist. Work through it sequentially, earlier items unblock later ones.</p><p><strong>Phase 1: Pre-migration (on Spring Boot 3.5.x)</strong></p><ul><li>[ ] Upgrade to Spring Boot 3.5.x (latest patch)</li><li>[ ] Add spring-boot-properties-migrator and fix all property warnings</li><li>[ ] Fix all deprecation warnings in your IDE (treat warnings as errors during this phase)</li><li>[ ] If using Undertow: switch to Tomcat or Jetty</li><li>[ ] Migrate WebSecurityConfigurerAdapter → SecurityFilterChain</li><li>[ ] Migrate authorizeRequests() → authorizeHttpRequests()</li><li>[ ] Migrate antMatchers() → requestMatchers()</li><li>[ ] Migrate all JUnit 4 tests → JUnit 5</li><li>[ ] Replace hibernate-jpamodelgen with hibernate-processor in the POM</li><li>[ ] Replace session.save(), session.update(), session.delete() with JPA standard calls</li><li>[ ] Remove spring-boot-properties-migrator before the version bump</li></ul><p><strong>Phase 2: The version bump</strong></p><ul><li>[ ] Update java.version to 21 in POM/Gradle</li><li>[ ] Update Docker base images to eclipse-temurin:21-jre (or 25-jre)</li><li>[ ] Update CI/CD Java version</li><li>[ ] Update Spring Boot version to 4.0.x</li><li>[ ] Run mvn dependency:tree | grep javax , any remaining javax.* (not jakarta.*) is a third-party library problem</li></ul><p><strong>Phase 3: Post-bump fixes</strong></p><ul><li>[ ] Migrate Jackson 2 custom serializers to Jackson 3 (tools.jackson.* packages)</li><li>[ ] Update ObjectMapper construction to JsonMapper.builder().build()</li><li>[ ] Update import org.springframework.lang.Nullable → import org.jspecify.annotations.Nullable</li><li>[ ] Run tests with spring.jpa.hibernate.ddl-auto=validate on staging</li><li>[ ] Audit explicit CSRF configuration in all SecurityFilterChain beans</li><li>[ ] Verify all POST/PUT/DELETE endpoints respond correctly</li></ul><h3>The Migration That’s Worth It</h3><p>Major version migrations are always painful. Spring Boot 4 is no exception.</p><p>But the specifics of each break are actually logical. Undertow couldn’t support Jakarta EE 11, it was never going to. Jackson 2 had reached the limits of its API design, Jackson 3’s JacksonException and builder pattern are cleaner. JUnit 4 has been superseded for years, there was never a good reason to keep carrying it. CSRF defaults that silently permitted unsafe configurations were a security risk, not a convenience.</p><p>Every change on this list is the Spring team cleaning up 10+ years of accumulated weight. The applications that come out the other side of this migration are leaner, more secure, and built on a stack that has a clear forward direction through Java 21, Jakarta EE 11, and the cloud-native infrastructure of the next five years.</p><p>The migration is the price of admission. The article you’re reading gives you the exact change to write in each room before you walk through the door.</p><p><em>Next in the Spring Boot Essentials 2026 series: </em><strong><em>Virtual Threads in Spring Boot 4: What Actually Changes for Your Code.</em></strong></p><h3>Beyond the Code: The Realities of Engineering</h3><p>Running a major framework migration in a production codebase means more than knowing what to fix. It means convincing your team it’s worth doing, managing the risk conversation with your tech lead, and owning the outcome when something breaks in staging at 11pm.</p><p>The technical skills get you to the door. What happens on the other side is a different set of skills entirely.</p><p>I’ve distilled the unwritten rules of navigating software engineering careers into a practical field guide.</p><p>👉 <a href="https://ankitv2717.gumroad.com/"><strong>Get “Beyond the Offer Letter” on Gumroad here</strong></a><strong>: </strong>and learn how software companies actually work so you can accelerate your engineering career.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60373ca4683e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-boot-4-migration-guide-what-breaks-and-how-to-fix-it-60373ca4683e">Spring Boot 4 Migration Guide: What Breaks and How to Fix It</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Leyden Deep Dive: How the JVM Is Finally Winning the Startup War]]></title>
            <link>https://medium.com/javarevisited/project-leyden-deep-dive-how-the-jvm-is-finally-winning-the-startup-war-f1b86d13e556?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1b86d13e556</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Sat, 16 May 2026 10:42:30 GMT</pubDate>
            <atom:updated>2026-05-16T10:42:30.099Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The JVM has always been powerful. For 30 years, its one unforgivable sin was making you wait. That’s changing, and the approach is smarter than anything the industry expected.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GVQHbJsgs-nby-xr" /><figcaption>Photo by <a href="https://unsplash.com/@dreyerchris?utm_source=medium&amp;utm_medium=referral">Chris Dreyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This is Article 3 in the Java Series. Article 1 covers the full state of Java in 2026. Article 2 explains how Virtual Threads made reactive programming optional.</em></p><p>In 2018, a Java architect at a major financial firm gave a conference talk. The title was blunt: <strong>“Why We’re Losing the Cloud-Native War.”</strong></p><p>His argument wasn’t about language features. It wasn’t about ecosystem or libraries. It was about one number: startup time.</p><p>Their Spring Boot services took 8 to 12 seconds to start cold. A Go microservice doing the same job started in 80 milliseconds. In a Kubernetes environment doing rolling deploys, horizontal autoscaling, and chaos engineering, those 8–12 seconds weren’t just slow, they were expensive. Cold starts in Lambda functions were nearly unusable. Autoscaling under burst load was sluggish. Every deployment meant a multi-second window where pods were starting but not serving.</p><p>The JVM, the most battle-tested, deeply optimized virtual machine in the history of computing, had a startup problem.</p><p>The industry’s initial answer was <strong>GraalVM Native Image</strong>: abandon the JVM at runtime, compile ahead of time, ship a native binary. Start in milliseconds.</p><p>It worked. It also introduced an entirely new set of problems that teams are still fighting with today.</p><p><strong>Project Leyden is a different answer.</strong> Not “abandon the JVM.” Instead: <em>teach the JVM to remember what it already did.</em></p><p>This article is a deep dive into how Leyden works, what it has delivered across JDK 24, 25, and 26, and how it compares to the GraalVM approach in real production scenarios.</p><h3>First: Why the JVM Starts Slowly</h3><p>To understand what Leyden fixes, you have to understand exactly where the JVM spends time during startup.</p><p>When you run java -jar myapp.jar, the JVM performs a sequence of expensive, redundant operations on every single launch:</p><h3>Phase 1: Class Loading</h3><p>The JVM reads .class files from disk (or jar entries), parses their bytecode format, validates their structure, and loads them into memory. A typical Spring Boot application loads <strong>5,000 to 15,000 classes</strong> during startup. Each class load involves disk I/O, bytecode parsing, and memory allocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*bye6Qac6FpW6f8CXm9TAgw.png" /><figcaption>Every startup. Every time. The same 8,000 classes. The same parsing. The same validation.</figcaption></figure><h3>Phase 2: Class Linking</h3><p>After loading, the JVM links classes: it verifies bytecode semantics, resolves symbolic references between classes, and prepares static fields. This is more CPU work applied to the same classes, again and again, on every boot.</p><h3>Phase 3: JIT Warmup</h3><p>The JVM starts executing bytecode immediately after linking. But it starts in interpreted mode, significantly slower than native code. The <strong>HotSpot JIT compiler</strong> identifies “hot” methods (methods called frequently) and compiles them to optimized native code at runtime.</p><p>This warmup process takes time. Depending on the application, it can take <strong>30 seconds to several minutes</strong> before the JVM is executing at peak throughput.</p><p>For long-running services, warmup is a one-time cost. For short-lived serverless functions, pods that scale in under load, or jobs that restart frequently, warmup is paid <em>every single time</em>.</p><p><strong>The cruel irony of traditional JVMs:</strong> they’re extraordinarily fast at steady state, but you have to run through a slow-motion setup process to get there, every time you restart.</p><h3>The Class Data Sharing Precedent</h3><p>Project Leyden didn’t invent the idea of caching JVM work. That idea started with <strong>Class Data Sharing (CDS)</strong>, introduced in Java 1.5 and significantly improved through Java 13+.</p><p>CDS works like this: instead of loading the JDK’s own core classes from scratch on every startup, the JVM can be told to create a <strong>shared archive</strong> (a .jsa file) containing pre-parsed, pre-linked versions of the JDK core classes. On subsequent runs, those classes are loaded directly from the archive via memory-mapped I/O, no re-parsing, no re-linking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*fH3Hf8vh4SqgTk2vvFYTLQ.png" /></figure><p>AppCDS works. Production benchmarks consistently show <strong>20–30% startup improvement</strong> just from caching the JDK classes plus the application’s own class metadata.</p><p>But CDS only addresses Phase 1 (class loading) and Phase 2 (class linking) partially. It doesn’t touch JIT warmup. And the workflow, dump list, create archive, run with archive, is tedious, error-prone, and breaks if your application changes.</p><p><strong>Project Leyden takes CDS and extends it in three progressive directions:</strong></p><ol><li><strong>AOT Class Loading &amp; Linking: </strong>A better CDS. More complete, more automatic. (JDK 24, JEP 483)</li><li><strong>AOT Method Profiling: </strong>Cache the JIT compiler’s decision-making history. (JDK 25, JEP 515)</li><li><strong>AOT Object Caching: </strong>Cache actual heap objects from the initialization phase. (JDK 26, JEP 516)</li></ol><p>Each JEP builds on the previous. Together, they represent a complete rethinking of when JVM work happens.</p><h3>The Architecture: Training Runs and Condensers</h3><p>Before covering each JEP, the architectural concept that underlies all of Leyden: <strong>training runs</strong> and <strong>condensers</strong>.</p><h3>The Training Run</h3><p>A <strong>training run</strong> is a deliberate, representative execution of your application whose purpose is <em>observation</em>, not production serving.</p><p>You run your application exactly as it would run in production, same configuration, same dependencies, same startup sequence, same warm-up traffic. But during this run, the JVM watches and records:</p><ul><li>Which classes were loaded and in what order</li><li>How those classes were linked and resolved</li><li>Which methods were called frequently enough to trigger JIT compilation</li><li>What the JIT’s optimization decisions looked like after warmup</li><li>What heap objects were allocated during initialization</li></ul><p>This recorded state is written to an <strong>AOT cache, </strong>a persistent file that captures everything the JVM learned.</p><p>On every subsequent production start, the JVM reads the AOT cache and <em>restores</em> that state, skipping the work it already did during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*Fcnw4iATDxevCN6F_mq7gA.png" /></figure><h3>Condensers</h3><p>The Leyden team uses the term <strong>condenser</strong> to describe the pipeline step that transforms a running program’s observed state into a compressed, persistent form. The condenser concept is deliberately extensible, today it captures class data, method profiles, and heap objects. In future JDK versions, it may capture more.</p><p>The key insight: <strong>a condenser shifts work left</strong>. Work that used to happen at runtime, on every startup, now happens once at build/training time, and the result is reused forever after.</p><p>This is the same conceptual move that compilers made decades ago, shift work from runtime to compile time. Leyden applies that idea to the JVM’s own initialization pipeline.</p><h3>JEP 483: AOT Class Loading &amp; Linking (JDK 24)</h3><p>JEP 483, delivered in JDK 24, is the first major Leyden feature in production. It extends AppCDS from a workflow-heavy, partial solution into a streamlined, comprehensive one.</p><h3>What It Captures</h3><p>Where AppCDS cached class <em>metadata</em> (parsed bytecode structure), JEP 483 captures the full class loading and linking state:</p><ul><li><strong>Class identity: </strong>the exact bytecode of each loaded class</li><li><strong>Linking state: </strong>resolved symbolic references, static field preparation</li><li><strong>Loader constraints: </strong>which classloader loaded which class</li><li><strong>Verification results: </strong>bytecode verification has already been done; don’t repeat it</li></ul><h3>The New Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*QAIauXNQijQwJ5HOosVLdA.png" /></figure><p>Two flags. The training run creates the cache. Every production run loads it.</p><p>Compare this to the old AppCDS workflow: three steps, two intermediate files, manual class list management. JEP 483 collapses the friction.</p><h3>What You Get</h3><p>In JDK 24 benchmarks on a typical Spring Boot application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*lTYUiO2m5ekJqiQLyrzAhA.png" /></figure><p>Class loading time is largely eliminated. Linking time is largely eliminated. The JVM wakes up with its class hierarchy already in place.</p><h3>JEP 515: AOT Method Profiling (JDK 25)</h3><p>JEP 483 addressed startup time, the time from java -jar to &quot;application is initialized.&quot; But it didn&#39;t address <strong>warmup time, </strong>the time from &quot;initialized&quot; to &quot;running at peak throughput.&quot;</p><p>The JIT compiler’s job is to find hot methods and compile them to optimized native code. This takes time because the JIT has to observe which methods are actually hot, then compile them.</p><p><strong>JEP 515, in JDK 25, caches the JIT compiler’s profile from the training run.</strong></p><h3>How JIT Profiling Works</h3><p>The HotSpot JIT compiles methods in tiers:</p><ol><li><strong>Tier 1 (Interpreted)</strong>: Bytecode runs in the interpreter. Slow, but the JVM collects profiling data.</li><li><strong>Tier 3 (C1 compiled)</strong>: The method has been called enough that the JVM compiles it to lightly-optimized native code. Still collects profiles.</li><li><strong>Tier 4 (C2 compiled)</strong>: The method is <em>hot</em>. The JVM uses the collected profiles to apply aggressive optimizations, inlining, loop unrolling, speculative deoptimization, escape analysis.</li></ol><p>The profiles that drive Tier 4 compilation take time to build. On a cold JVM, it can take 30+ seconds of live traffic before critical code paths hit Tier 4.</p><h3>What JEP 515 Does</h3><p>The training run, in addition to recording class loading state, now also records the <strong>method execution profiles</strong> that the JIT accumulated.</p><p>On a subsequent production start:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*Gt4am94_H2KtULMA1dyGrQ.png" /></figure><h3>The Code Impact</h3><p>From your application’s perspective, nothing changes. No annotations, no build plugins, no code modifications. The JVM handles this transparently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*SiOei3L2kT6E2Sf470foUQ.png" /></figure><p>The AOT cache now contains two things: class loading state <em>and</em> JIT method profiles. One file, one flag.</p><h3>Measured Impact</h3><p>The combination of JEP 483 + JEP 515 shows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*hiwkXDimTnE4KLHwe16REg.png" /></figure><p>The JIT still runs in production. Profiles are a starting point, not a ceiling. If production traffic differs from training traffic, the JIT adapts. This is the fundamental difference from static AOT compilation: Leyden’s optimization is adaptive, not frozen.</p><h3>JEP 514: AOT Command-Line Ergonomics (JDK 25)</h3><p>JEP 514, also in JDK 25, is a quality-of-life improvement that makes the Leyden workflow practical for CI/CD environments.</p><p>Before JEP 514, creating the AOT cache required a multi-step workflow: run in record mode, then run in create mode, then run in production mode. Each step had different flags.</p><p>JEP 514 introduces <strong>one-shot cache creation</strong> with the -XX:AOTCacheOutput flag, which automatically handles both the recording and serialization phases in a single run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*bBCTxQOoF7SA2kwZQQdKaQ.png" /></figure><p>For CI/CD pipelines, this translates directly to simpler Dockerfiles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*pDD0Ca3rqD-7nuEw16is8g.png" /></figure><p>The AOT cache is built once, baked into the image, and used on every container start. Zero per-startup overhead for class loading or JIT warmup.</p><h3>JEP 516: AOT Object Caching with Any GC (JDK 26)</h3><p>JEP 516 is the most architecturally ambitious Leyden feature delivered so far, and the one that directly unlocks Spring Boot’s most expensive startup cost.</p><h3>The Problem: Heap Initialization</h3><p>After class loading and JIT warmup, a Spring Boot application’s remaining startup cost is <strong>object initialization</strong>: the Spring ApplicationContext is building. It’s:</p><ul><li>Scanning classpath for @Component, @Service, @Repository annotations</li><li>Creating and wiring beans</li><li>Instantiating connection pools</li><li>Building serialization/deserialization metadata (Jackson, for example)</li><li>Loading reference data from databases or config files</li></ul><p>This work produces heap objects, potentially thousands of them. And these objects are identical on every startup. The Spring ApplicationContext for a given application produces the same bean graph every single time.</p><p><strong>Why does the JVM rebuild this from scratch every restart?</strong></p><h3>What JEP 516 Does</h3><p>JEP 516 allows the AOT cache to include <strong>heap objects, </strong>actual live Java objects, serialized into the cache during the training run and materialized back into the heap at startup.</p><p>During the training run, after the application has fully initialized, the JVM can freeze a snapshot of specified heap regions and write them into the AOT cache. On subsequent starts, those objects are <strong>streamed back into the heap</strong> without re-executing the initialization code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*d32M9NvJ6pUwsOoLugP8og.png" /></figure><h3>The GC-Agnostic Streaming Format</h3><p>The technical challenge JEP 516 solved is non-trivial. Previous attempts at heap object caching failed with <strong>Generational ZGC</strong> (the preferred collector in 2026) because ZGC uses <em>colored pointers, </em>object references include metadata bits in the pointer address itself. ZGC’s object layout is fundamentally incompatible with a naively memory-mapped object snapshot.</p><p>JEP 516’s solution: instead of memory-mapping cached objects (which requires a GC-specific layout), it uses a <strong>GC-agnostic streaming format</strong>. Objects are serialized as a structured byte stream during the training run. At startup, they are <strong>deserialized and materialized</strong> according to the GC currently in use, ZGC gets ZGC-format objects, G1 gets G1-format objects.</p><p>This makes the AOT cache portable across all supported GC configurations. One cache file works whether you’re using G1, ZGC, or Generational ZGC.</p><h3>Combined Impact: All Three JEPs Together</h3><p>With JEP 483 + 515 + 516, a benchmarked Spring Boot application shows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*e_eP8USbtw2mWtjAwrKSzQ.png" /></figure><p>That’s roughly a <strong>6x startup improvement</strong> on a real Spring Boot service, without changing a single line of application code, without GraalVM, without native image compilation.</p><h3>Leyden vs. GraalVM Native Image: A Serious Comparison</h3><p>This is the comparison that gets oversimplified everywhere. Let’s be precise.</p><h3>The Philosophical Difference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*EuFcLI4aqs2Unkjvw9lfoQ.png" /></figure><h3>When GraalVM Native Image Still Wins</h3><p><strong>AWS Lambda and cold-start-sensitive FaaS:</strong> If you’re paying for every millisecond of cold start latency, and Lambda’s billing model means you are, GraalVM’s sub-100ms startup is worth the configuration investment. Leyden’s 300–500ms is still dramatically better than the JVM baseline, but Native Image remains king at the absolute latency floor.</p><p><strong>Extremely memory-constrained environments:</strong> Embedded systems or edge nodes where the JVM’s base memory overhead (~50–100MB) is unacceptable. Native Image binaries start at 10–15MB.</p><p><strong>Applications with completely static behavior:</strong> If your application has no runtime reflection, no dynamic class loading, and no runtime proxies, a simple CLI utility, for example, Native Image is straightforward to configure and delivers maximum performance.</p><h3>When Leyden Is the Better Answer</h3><p><strong>Complex enterprise frameworks:</strong> Spring Boot, Hibernate, Jackson, all rely heavily on reflection, dynamic proxies, and runtime class generation. Getting these to work under GraalVM’s closed-world constraints requires extensive reachability metadata configuration. Each new library you add potentially breaks native compilation. Leyden handles all of this transparently.</p><p><strong>Teams that can’t afford native image maintenance:</strong> GraalVM native image compilation is a build-time engineering discipline. You need someone who understands reachability analysis, can diagnose subtle native image failures, and can manage the metadata configuration as dependencies evolve. Not every team has this capacity.</p><p><strong>Peak throughput matters:</strong> If your service runs long (containers with multi-hour lifetimes, not ephemeral serverless functions), the JIT compiler’s adaptive optimization pays dividends that static AOT compilation cannot match. A JIT-optimized method can outperform its AOT equivalent by 20–40% on data-structure-heavy workloads.</p><p><strong>Development velocity:</strong> Leyden requires zero application code changes. GraalVM requires ongoing testing of native compilation success. For teams shipping features rapidly, the difference in friction is significant.</p><h3>Applying Leyden in Practice: A Spring Boot 4 Walkthrough</h3><p>Here’s a practical, production-ready Leyden integration for a Spring Boot 4 service.</p><h3>Project Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*ygSMqBIjWjslf0XGdKftoA.png" /></figure><h3>Step 1: Ensure You’re on JDK 25 or 26</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*_rXHlT5hBx2x7Srce-ts2A.png" /></figure><h3>Step 2: Build the Jar Normally</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*YL3LSdOsA-uGBRGxrCrpaw.png" /></figure><h3>Step 3: Create the Training Run</h3><p>The training run should exercise your application’s actual startup sequence. If your app needs to warm up HTTP endpoints, call them during the training run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*_tFIRT4cTJzedfuQ-KgKWA.png" /></figure><h3>Step 4: Dockerfile with AOT Cache</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*kt-NfLwEcN0P28l8FtG_Ag.png" /></figure><h3>Step 5: Verify the Cache Is Being Used</h3><p>The JVM provides logging to confirm the AOT cache is active:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*H5l6-8cC0ELJuXoY5YpLqA.png" /></figure><p>Look for output like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*0E05s_f09-XhiWPiFlriTA.png" /></figure><h3>What to Watch Out For</h3><p><strong>Training representativeness is critical.</strong> If your training run doesn’t exercise a code path that gets called heavily in production, that path won’t have JIT profiles in the cache and will warm up cold. For maximum benefit, your training run’s traffic should be as close to production traffic as possible.</p><p><strong>The cache is invalidated when your jar changes.</strong> If you deploy a new version, you need a new training run and a new cache. This is expected behavior, bake cache generation into your CI/CD pipeline.</p><p><strong>Class loading from new sources breaks the cache.</strong> If your application dynamically loads classes at runtime (plugin systems, hot-reload frameworks), those classes won’t be in the cache. Leyden handles this gracefully, it falls back to normal class loading, but you won’t get caching benefits for those paths.</p><h3>The Bigger Picture: What Leyden Means for Java’s Future</h3><p>Project Leyden is not just a startup optimization. It represents a maturing of the “shift left” principle applied to the JVM.</p><p>For 30 years, the JVM’s value proposition was: <em>“We’ll optimize aggressively at runtime, using information we only know after the program starts running.”</em> The JIT is the embodiment of this philosophy, it waits to see what code is actually hot before spending cycles compiling it.</p><p>Leyden doesn’t abandon that philosophy. It augments it: <em>“We’ll also remember what we learned from previous runs, so we don’t have to re-learn it every time.”</em></p><p>The condenser model is extensible. Today it captures class data, JIT profiles, and heap objects. In future JDK releases, it may capture:</p><ul><li>Reflection resolution results (the table of “this class has these methods”)</li><li>Dynamic proxy class structures (Spring’s AOP proxies are generated once, cached forever)</li><li>Database connection pool initialization state</li><li>Configuration parsing results</li></ul><p>Each extension pushes startup further toward the theoretical limit: a JVM that starts exactly where it left off.</p><p>This is the vision the Leyden team described in their original proposal: <strong>a JVM that is not just fast at steady state, but fast from the first instruction of every run.</strong></p><h3>What This Means for Your Architecture Decisions Right Now</h3><p><strong>If you’re building a new Java service in 2026:</strong> Design your Dockerfile to include a training run from the start. It’s a 15-minute investment that pays dividends on every deployment.</p><p><strong>If you’re running Java services on Kubernetes:</strong> Leyden’s startup improvement directly reduces the window during rolling deployments where pods are starting but not serving. Tighter startup = smoother deploys = less need for overly conservative startupProbe timeouts.</p><p><strong>If you’ve been using GraalVM Native Image:</strong> Re-evaluate. If you’re spending significant engineering time managing reachability metadata and native image build failures, Leyden now provides 80% of the startup benefit with 5% of the operational complexity.</p><p><strong>If your team dismissed Java for Go or Python for startup reasons:</strong> The argument has expired. A Leyden-optimized Spring Boot service starts in 300–500ms. That’s Go territory, with the full Java ecosystem behind it.</p><h3>The State of the War</h3><p>The startup war was never just about milliseconds. It was about whether Java, with all its ecosystem maturity, its enterprise reliability, its extraordinary runtime performance, could be a first-class citizen in modern cloud-native infrastructure.</p><p>For years, the honest answer was: not quite.</p><p>GraalVM offered an exit, but it was a costly one, trading ecosystem compatibility for startup speed, maintenance simplicity for performance extremes.</p><p>Leyden offers something better: <strong>you don’t have to choose.</strong> Keep the JVM. Keep the full ecosystem. Keep the JIT’s adaptive optimization. Just tell the JVM to remember what it already knows.</p><p>It took 30 years for the Java platform to arrive at this answer. The answer was worth waiting for.</p><p><em>Next in the Java Series: </em><strong><em>Project Valhalla Deep Dive: Value Classes and Why Every Java Collection Will Change.</em></strong></p><h3>Beyond the Code: The Realities of Engineering</h3><p>Understanding Project Leyden tells you <em>how</em> the JVM is evolving. But knowing <em>when</em> to advocate for a Java upgrade at your company, how to make the performance case to a risk-averse team, and how to position yourself as the engineer who leads platform decisions, that’s a different skill set entirely.</p><p>I’ve distilled the unwritten rules of navigating software engineering careers into a practical field guide.</p><p>👉 <a href="https://ankitv2717.gumroad.com/"><strong>Get “Beyond the Offer Letter” on Gumroad here</strong></a><strong>: </strong>and learn how software companies actually work so you can accelerate your growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1b86d13e556" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/project-leyden-deep-dive-how-the-jvm-is-finally-winning-the-startup-war-f1b86d13e556">Project Leyden Deep Dive: How the JVM Is Finally Winning the Startup War</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I’m Building an Open-Source Runtime Memory Simulator, And I Want Your Input]]></title>
            <link>https://medium.com/illumination/im-building-an-open-source-runtime-memory-simulator-and-i-want-your-input-97a13656a476?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/97a13656a476</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Tue, 12 May 2026 05:56:24 GMT</pubDate>
            <atom:updated>2026-05-12T05:56:24.628Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A visual, interactive tool for understanding how garbage collectors and memory managers actually behave, across JVM and Node.js.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hNYRIqQpBfLtVO6w" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here’s something I’ve noticed after years of backend engineering.</p><p>Most developers, including experienced ones, have a vague, approximate understanding of how garbage collection works.</p><p>They know it “frees memory.” They know it “causes pauses.” They’ve seen the GC logs, maybe tuned a flag or two in production. But ask them what actually happens inside the JVM when G1 GC fires a mixed collection, or why ZGC can collect concurrently while your application threads keep running, or how Generational ZGC in Java 21 is fundamentally different from the original ZGC in Java 17, and most engineers go quiet.</p><p>That knowledge gap has real consequences. GC-related issues are some of the hardest production problems to diagnose precisely because most engineers can’t visualize what’s happening.</p><p>That’s what I’m trying to fix.</p><h3>What I’m Building</h3><p>I’m building an <strong>open-source, visual, interactive runtime memory simulator, </strong>a tool that lets you watch garbage collectors and memory managers work in real time, side by side, at your own pace.</p><p>The project is called <strong>JVM GC Algorithms</strong> and it’s currently live on GitHub.</p><p>The current version is a Java/Spring Boot backend with an Angular frontend. It simulates <strong>10 garbage collection algorithms</strong> across Java 8, Java 17, and Java 21:</p><p><strong>Java 8 era:</strong></p><ul><li>Serial GC</li><li>Parallel GC</li><li>CMS (Concurrent Mark Sweep)</li><li>G1 GC</li></ul><p><strong>Java 17 era:</strong></p><ul><li>Enhanced G1 GC</li><li>ZGC</li><li>Shenandoah GC</li></ul><p><strong>Java 21 era:</strong></p><ul><li>Latest G1 GC</li><li>Generational ZGC</li><li>Generational Shenandoah</li></ul><p>For each algorithm, you can:</p><ul><li><strong>Allocate objects</strong> manually (50 at a time) or let the simulator run automatically</li><li><strong>Watch live memory bars</strong> for Eden, Survivor-0, Survivor-1, Old Generation, and Metaspace fill up in real time</li><li><strong>Trigger GC manually</strong> and observe exactly what happens, which regions are collected, what’s promoted, what pause time occurs</li><li><strong>Compare pause times</strong> across algorithms as you switch between them</li><li><strong>Read the GC event log</strong> which describes what happened at each collection cycle</li></ul><p>The goal is not just to show that ZGC is faster than Serial GC. It’s to let you <em>see</em> why. To watch the difference between a stop-the-world pause and a concurrent collection. To understand what “Eden is full” actually means for allocation performance.</p><h3>Why I Built This</h3><p>I’ve been writing about the JVM on Medium for a while now, Virtual Threads, Project Loom, Java 25, the whole generational GC evolution. And the feedback I consistently get is some version of:</p><blockquote>“I understand the words. I just can’t picture it.”</blockquote><p>Reading about garbage collection is one thing. Watching it happen, allocating objects, seeing Eden fill up, watching the GC kick in and reclaim space, observing the pause time, is something completely different.</p><p>A lot of GC tutorials show static diagrams. Heap regions with arrows. Before/after states. These are fine for introducing concepts, but they don’t show the <em>dynamic</em> nature of memory management, the continuous cycle of allocation, collection, promotion, and compaction that runs throughout your application’s entire lifetime.</p><p>I wanted to build something you could interact with, not just read.</p><h3>What’s Coming Next, Node.js Runtime</h3><p>Here’s where I’d love your feedback most.</p><p>The JVM GC simulator is the first runtime. The next one I’m planning to add is <strong>Node.js, </strong>and this is where it gets more interesting.</p><p>Node.js uses the <strong>V8 garbage collector</strong>, which is completely different in design from JVM collectors. V8 is generational (young space / old space), uses a scavenger algorithm for young generation collection, and has a mark-compact collector for old generation. It also has a completely different memory ceiling, V8’s default heap is limited to around 1.5GB on 64-bit systems, which is a real constraint Node.js developers hit in production.</p><p>Adding Node.js would mean:</p><ul><li>Simulating V8’s <strong>young space (Scavenge)</strong> vs <strong>JVM’s Eden + Minor GC</strong></li><li>Visualizing V8’s <strong>old space (Mark-Compact)</strong> vs <strong>JVM’s Old Generation (Major/Full GC)</strong></li><li>Showing the fundamental difference between the JVM’s mature, tunable GC ecosystem and V8’s streamlined but constrained model</li><li>Side-by-side comparisons, what does handling the same allocation pattern look like in the JVM vs V8?</li></ul><p>The idea is to make this a <strong>cross-runtime memory education tool</strong>, not just a JVM-specific one.</p><h3>What I Want to Know From You</h3><p>This is genuinely early-stage planning. Before I build further, I want feedback from the people who would actually use this.</p><p><strong>A few specific questions:</strong></p><p><strong>1. What would make this useful to you as a learning tool?</strong> Is the current simulation-based approach the right format? Would you rather have guided walkthroughs explaining what you’re seeing, or do you prefer exploring freely?</p><p><strong>2. What other runtimes or scenarios matter to you?</strong> Node.js V8 is my next target. But would Python’s memory model (reference counting + cyclic GC) be useful? Go’s tri-color mark-and-sweep? Are there specific JVM collectors you’d want to see compared: for example, ZGC vs Shenandoah vs G1 for the same allocation workload?</p><p><strong>3. What do you find hardest to understand about GC right now?</strong> Is it the algorithm differences? The tuning flags? When to use which collector? Understanding what GC logs are telling you? Knowing what’s happening when your production app pauses unexpectedly?</p><p><strong>4. What features are missing that you’d want?</strong> A few ideas I’m considering:</p><ul><li><strong>Benchmark mode: </strong>run the same workload across multiple algorithms and show a comparison table of pause times, throughput, and memory efficiency</li><li><strong>Preset scenarios: </strong>“simulate a high-allocation microservice,” “simulate a batch job,” “simulate a long-running background process”</li><li><strong>GC log importer: </strong>paste your actual production GC logs and visualize them in the same interface</li><li><strong>Memory leak simulation: </strong>watch what happens to Old Gen when objects are never released</li></ul><p>Are any of these compelling? Are there things not on this list that would make this genuinely useful in your day-to-day work?</p><h3>The GitHub Repo</h3><p>The project is open source and the current version is live:</p><p><strong>→ </strong><a href="https://github.com/ankitverma2717/JVM-GC-Collection-Algorithms"><strong>github.com/ankitverma2717/JVM-GC-Collection-Algorithms</strong></a></p><p>It runs with a single Gradle command, no installation required. If you want to try it, clone it, run ./gradlew run, and see how far you get before something confuses you. That confusion is useful feedback too.</p><h3>Why This Matters Beyond the Tool</h3><p>There’s a broader point I want to make.</p><p>The engineers who understand GC at a deeper level are the ones who can:</p><ul><li>Look at a production GC log and tell you exactly why the application slowed down at 3am</li><li>Tune -XX:MaxGCPauseMillis with confidence instead of guessing</li><li>Explain to a non-technical stakeholder why “adding more heap” won’t fix the problem</li><li>Make a real argument for switching from G1 to ZGC in a latency-sensitive service</li></ul><p>That knowledge gap between “I’ve heard of garbage collection” and “I understand how my runtime manages memory” is where a lot of production incidents live.</p><p>A tool that closes that gap, even partially, is worth building.</p><h3>Leave Your Feedback</h3><p>I read every response. If you have thoughts, about the existing simulator, about the Node.js addition, about features you’d want, or about GC concepts you’ve always found confusing, leave a comment below.</p><p>This is the kind of project that gets better with input from people who actually work with these systems. I’d rather know what you need before I build it than after.</p><p>Also You can also email me at ankit.dev273@gmail.com<br>or send me a DM with your feedback on <a href="https://www.linkedin.com/in/ankit2717/">Linkedin</a>. I would also be happy to connect with you there!</p><p><em>If you’re new here: I write about Java, the JVM, backend systems, and distributed architecture. The GC simulator is part of a broader effort to make complex systems concepts visual and interactive. Follow along if that’s useful to you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97a13656a476" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illumination/im-building-an-open-source-runtime-memory-simulator-and-i-want-your-input-97a13656a476">I’m Building an Open-Source Runtime Memory Simulator, And I Want Your Input</a> was originally published in <a href="https://medium.com/illumination">ILLUMINATION</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtual Threads in Spring Boot 4: What Actually Changes for Your Code]]></title>
            <link>https://medium.com/javarevisited/virtual-threads-in-spring-boot-4-what-actually-changes-for-your-code-9b490b57f400?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b490b57f400</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Wed, 06 May 2026 15:51:18 GMT</pubDate>
            <atom:updated>2026-05-18T05:55:20.198Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You’ve enabled virtual threads. Now what? Here’s what actually changes, and what breaks.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kYQjwQwz5zS-QB6z" /><figcaption>Photo by <a href="https://unsplash.com/@deepakrautela?utm_source=medium&amp;utm_medium=referral">Deepak Rautela</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This is Article 4 in the Spring Boot Essentials 2026 series. In Article 3, </em><strong><em>Spring Boot Essentials 2026: Everything That Changed from Spring 6 to Spring 7</em></strong><em>, we covered BeanRegistrar, JSpecify null safety, native API versioning, modularization into 70+ granular modules, and the full dependency purge. </em><a href="https://medium.com/illumination/spring-boot-essentials-2026-the-ultimate-guide-to-spring-framework-7-vs-spring-6-9b705f1d5e9c"><em>Read here. </em></a><em><br>Up next in Article 5, </em><strong><em>Spring Boot 4 Migration Guide: What Breaks and How to Fix It</em></strong><em>, we walk through every breaking change, Undertow removal, Jackson 3 serializer migration, JUnit 4 removal, Spring Security defaults, and Hibernate 7, with the exact code to fix each one. </em><a href="https://medium.com/javarevisited/spring-boot-4-migration-guide-what-breaks-and-how-to-fix-it-60373ca4683e"><em>Read here.</em></a></p><p>Most Spring Boot developers who’ve heard about Virtual Threads have the same reaction:</p><blockquote>“I know they exist. I know they’re good. I have no idea what I actually need to change in my application.”</blockquote><p>That’s the right question. Because enabling Virtual Threads in Spring Boot is deceptively simple, one property, and you’re done. But that simplicity hides a set of behavioral changes that will surprise you if you don’t understand them.</p><p>Some things get better automatically. Some things you need to rethink. And some things will quietly break if you don’t know where to look.</p><h3>What Virtual Threads Are (The 30-Second Version)</h3><p>Traditional Java threads map 1:1 with OS threads. Each OS thread consumes about 1MB of stack memory. Your JVM can realistically handle a few hundred to a few thousand before memory and context-switching become serious problems.</p><p>Virtual Threads are JVM-managed. They’re cheap, you can have millions. When a Virtual Thread blocks on I/O, the JVM automatically unmounts it from its carrier OS thread, freeing that carrier thread for other work. When the I/O completes, the Virtual Thread resumes.</p><p>The result: <strong>simple, blocking, synchronous code that scales to concurrency levels that previously required reactive programming.</strong></p><h3>Enabling Virtual Threads in Spring Boot</h3><pre># application.properties<br>spring.threads.virtual.enabled=true</pre><p>One line. With this set:</p><ul><li>Tomcat’s request-handling threads become Virtual Threads</li><li>Spring’s @Async executor uses Virtual Threads</li><li>SimpleAsyncTaskExecutor defaults to Virtual Threads</li></ul><p>Your application code doesn’t change. The framework handles the rest.</p><h3>What Gets Better: Automatically</h3><h3>1. Throughput on I/O-Bound Endpoints</h3><p>If your endpoints spend most of their time waiting, database queries, downstream service calls, cache lookups, Virtual Threads improve your throughput without any code changes.</p><p>With traditional threads, a blocked thread holds its OS thread hostage. With Virtual Threads, the OS thread is released the moment blocking I/O begins.</p><h3>2. @Async Just Works</h3><pre>@Service<br>public class EmailService {</pre><pre>    @Async<br>    public CompletableFuture&lt;Void&gt; sendWelcomeEmail(String userEmail) {<br>        smtpClient.send(userEmail, &quot;Welcome!&quot;);<br>        return CompletableFuture.completedFuture(null);<br>    }<br>}</pre><p>Spring automatically configures a SimpleAsyncTaskExecutor backed by Virtual Threads for @Async methods. You no longer need a manually tuned ThreadPoolTaskExecutor for I/O-bound async work.</p><h3>3. No More Tomcat maxThreads Tuning</h3><pre># Old: had to tune this carefully to avoid memory pressure<br>server.tomcat.threads.max=200</pre><pre># New: remove it. Virtual Threads make this limit irrelevant for most workloads.</pre><p>With Virtual Threads, Tomcat creates a new Virtual Thread per request. The maxThreads cap no longer represents a scarce resource. You can remove this tuning property entirely.</p><h3>What You Need to Rethink</h3><h3>1. Your Database Connection Pool Is Now the Real Bottleneck</h3><p>This is the most important change developers miss.</p><p>With traditional threads, your connection pool size was loosely aligned with your thread pool. 200 Tomcat threads → 20 HikariCP connections made sense because not all threads hit the database simultaneously.</p><p>With Virtual Threads, you can have thousands of concurrent requests, all potentially needing a database connection at the same time. The pool becomes the new bottleneck.</p><pre># Before Virtual Threads<br>server.tomcat.threads.max=200<br>spring.datasource.hikari.maximum-pool-size=20</pre><pre># After Virtual Threads<br># spring.threads.virtual.enabled=true<br>spring.datasource.hikari.maximum-pool-size=50  # recalibrate upward</pre><p>Important: database connections are still expensive <strong>on the database side</strong>. PostgreSQL has its own connection limit. A pool of 1,000 will likely overwhelm your database server regardless of how many virtual threads your app can handle. Benchmark your database’s comfortable concurrency ceiling and set the pool to that.</p><p>This is the most common mistake after enabling Virtual Threads: the bottleneck shifts from thread count to connection count, and teams don’t notice until load testing.</p><h3>2. synchronized Blocks: The Pinning Problem</h3><p>When a Virtual Thread encounters a synchronized block and blocks inside it, the JVM <strong>cannot unmount it from its carrier OS thread</strong>. The Virtual Thread is &quot;pinned&quot;, it holds the carrier thread hostage, exactly like a traditional platform thread would.</p><pre>// Causes pinning, Virtual Thread holds the OS carrier thread while blocking<br>public synchronized void updateSharedState() {<br>    jdbcTemplate.update(&quot;...&quot;); // I/O inside synchronized = pinning<br>}</pre><pre>// Fix: use ReentrantLock instead<br>private final ReentrantLock lock = new ReentrantLock();</pre><pre>public void updateSharedState() {<br>    lock.lock();<br>    try {<br>        jdbcTemplate.update(&quot;...&quot;);<br>    } finally {<br>        lock.unlock();<br>    }<br>}</pre><p>Your own code you can audit. The bigger concern is <strong>library code: </strong>some JDBC drivers and older connection pool implementations use synchronized internally.</p><p><strong>Detecting pinning during load tests:</strong></p><pre># Add this JVM flag: prints pinning events to stdout<br>-Djdk.tracePinnedThreads=full</pre><p>If you see frequent pinning in hot paths, investigate which dependency is responsible.</p><h3>3. ThreadLocal at Scale</h3><p>ThreadLocal still works with Virtual Threads. But with potentially millions of virtual threads each carrying ThreadLocal values, memory usage accumulates more than with a bounded thread pool.</p><p>The modern replacement is <strong>Scoped Values</strong> (stable in Java 25):</p><pre>// Old: ThreadLocal, must be cleaned up manually<br>static final ThreadLocal&lt;User&gt; CURRENT_USER = new ThreadLocal&lt;&gt;();</pre><pre>// Modern: Scoped Values, lifecycle is automatic<br>static final ScopedValue&lt;User&gt; CURRENT_USER = ScopedValue.newInstance();</pre><pre>// In your filter/interceptor<br>ScopedValue.runWhere(CURRENT_USER, authenticatedUser, () -&gt; {<br>    chain.doFilter(request, response);<br>});<br>// Value is gone after this block, no cleanup needed</pre><p>Spring’s security context propagation is already Virtual Thread-aware. For custom ThreadLocal usage (audit logs, trace IDs, tenant context), evaluate migrating to Scoped Values.</p><h3>Do You Still Need WebFlux?</h3><p>The honest answer: <strong>for most use cases, no. For some specific cases, yes.</strong></p><p><strong>You no longer need WebFlux for:</strong></p><ul><li>High-throughput REST APIs</li><li>Concurrent database or HTTP calls</li><li>Handling thousands of simultaneous users</li></ul><p><strong>WebFlux is still the right choice for:</strong></p><ul><li><strong>Server-Sent Events (SSE): </strong>streaming data over long-lived connections</li><li><strong>WebSocket: </strong>bidirectional real-time communication</li><li><strong>True backpressure: </strong>when your consumer can’t keep up with your producer</li><li><strong>Reactive data sources: </strong>R2DBC or reactive message brokers</li></ul><pre>// WebFlux still wins for SSE<br>@GetMapping(value = &quot;/events&quot;, produces = MediaType.TEXT_EVENT_STREAM_VALUE)<br>public Flux&lt;ServerSentEvent&lt;String&gt;&gt; streamEvents() {<br>    return Flux.interval(Duration.ofSeconds(1))<br>               .map(seq -&gt; ServerSentEvent.builder(&quot;event-&quot; + seq).build());<br>}</pre><p>If your application is pure REST, request in, response out, migrate to Spring MVC with Virtual Threads. If you have streaming or reactive data sources, keep WebFlux.</p><h3>Migration Checklist</h3><pre>[ ] Add spring.threads.virtual.enabled=true<br>[ ] Remove server.tomcat.threads.max if tuned for thread scarcity<br>[ ] Increase spring.datasource.hikari.maximum-pool-size based on DB capacity<br>[ ] Run load tests with -Djdk.tracePinnedThreads=full<br>[ ] Audit synchronized blocks in your code, replace with ReentrantLock where I/O is involved<br>[ ] Verify JDBC driver versions (PostgreSQL 42.6+, MySQL Connector/J 8.0.33+ are VT-friendly)<br>[ ] Remove unnecessary custom ThreadPoolTaskExecutor @Beans for I/O-bound async work<br>[ ] Evaluate WebFlux endpoints for potential MVC migration</pre><h3>The Mental Model Shift</h3><p>Traditional Spring Boot performance tuning was about <strong>managing scarce threads</strong>. You set maxThreads. You tuned the pool. You added reactive programming when threads became the bottleneck.</p><p>Virtual Threads change the question:</p><blockquote>“What are the actual shared resources that can be exhausted?”</blockquote><p>Database connections. External API rate limits. CPU cores for compute-bound work. Those are still real constraints. Virtual Threads remove threads from that list, but the others remain.</p><p>Tune for what’s actually scarce. That’s the job now.</p><p><em>Next in the Spring Boot Essentials 2026 series: </em><strong><em>Spring Boot 4 Migration Guide: What Breaks and How to Fix It.</em></strong></p><h3>Beyond the Code</h3><p>Knowing that Virtual Threads improve throughput is one thing. Convincing your team to migrate from a WebFlux codebase that’s been in production for two years, and navigating the rewrite risk, is an organizational problem, not a technical one.</p><p>I’ve distilled the unwritten rules of navigating decisions like these inside software companies into a practical field guide.</p><p>👉 <a href="https://ankitv2717.gumroad.com/"><strong>Get “Beyond the Offer Letter” on Gumroad here</strong></a>, and learn how software companies actually work so you can accelerate your growth</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b490b57f400" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/virtual-threads-in-spring-boot-4-what-actually-changes-for-your-code-9b490b57f400">Virtual Threads in Spring Boot 4: What Actually Changes for Your Code</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtual Threads: The Idea That Made Reactive Programming Optional]]></title>
            <link>https://medium.com/javarevisited/virtual-threads-the-idea-that-made-reactive-programming-optional-627943d3e78f?source=rss-17c656b80fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/627943d3e78f</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankit Verma]]></dc:creator>
            <pubDate>Wed, 06 May 2026 15:51:16 GMT</pubDate>
            <atom:updated>2026-05-18T06:50:07.006Z</atom:updated>
            <content:encoded><![CDATA[<p><em>For 10 years, reactive was the answer to concurrency at scale. Here’s why that changed, and what it means for the code you write.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UAZECQubccWvht5E" /><figcaption>Photo by <a href="https://unsplash.com/@austriannationallibrary?utm_source=medium&amp;utm_medium=referral">Austrian National Library</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is Article 2 in the Java series. In Article 1, <strong>Java in 2026: What the Language Actually Looks Like Today</strong>, we covered the full state of the platform — Virtual Threads and Project Loom, Project Amber’s syntax modernization, Scoped Values, Project Leyden’s startup approach, Valhalla, and Babylon. <a href="https://medium.com/illumination/the-evolution-of-java-in-2026-a-deep-dive-into-the-jvms-renaissance-b4eff4874320">Read here.</a></p><p>Up next in Article 3, <strong>Project Leyden Deep Dive: How the JVM Is Finally Winning the Startup War</strong>, we go deep on why the JVM starts slowly, how JEP 483 (AOT class loading), JEP 515 (AOT method profiling), and JEP 516 (AOT object caching) work together, and how it compares to GraalVM Native Image. <a href="https://medium.com/javarevisited/project-leyden-deep-dive-how-the-jvm-is-finally-winning-the-startup-war-f1b86d13e556">Read here.</a></p><p>In 2015, if you were building a Java service that needed to handle 10,000 concurrent requests, someone on your team would eventually say:</p><blockquote>“We need to go reactive.”</blockquote><p>And they weren’t wrong. Given the constraints of the time, reactive programming was the correct answer. It was also painful, complicated, and a constant source of subtle bugs.</p><p>In 2021, Project Loom entered preview. In 2023, it shipped in Java 21.</p><p>The conversation has changed. Reactive programming is no longer the only answer to concurrency at scale. In many cases, it’s no longer the best one.</p><p>This article explains why.</p><h3>The Problem Reactive Programming Was Solving</h3><p>To understand why Virtual Threads matter, you have to understand the exact problem reactive programming was designed to fix.</p><p>Traditional Java web servers: Tomcat &amp; Jetty, use a <strong>thread-per-request</strong> model. Every incoming HTTP request gets assigned a thread from a pool. That thread handles the request start to finish: parsing, business logic, database calls, response writing.</p><p>This works fine until requests start blocking.</p><p>A typical REST endpoint spends most of its time <strong>waiting</strong>:</p><ul><li>Waiting for a database query to return</li><li>Waiting for a downstream HTTP service to respond</li><li>Waiting for a cache lookup to complete</li></ul><p>While it waits, the thread does nothing, but it still exists, still consumes ~1MB of stack memory, and still counts against the pool limit.</p><pre>Thread pool: 200 threads<br>Concurrent requests: 200<br>Each request blocks for 100ms on a DB call</pre><pre>→ 200 threads, all blocked, all idle<br>→ Request 201 has to wait in a queue<br>→ Latency spikes<br>→ Users experience slowness</pre><p>The bottleneck wasn’t CPU. It was <strong>threads blocking on I/O</strong> while consuming memory and blocking the pool.</p><p>Reactive programming’s answer was to stop using threads as the unit of concurrency for I/O. Instead of one thread per request, you’d have a small number of threads (matching CPU cores) and an <strong>event loop, </strong>a mechanism where I/O operations register callbacks and release the thread immediately, processing the result later when the I/O completes.</p><pre>// Reactive, Project Reactor style<br>public Mono&lt;UserProfile&gt; getProfile(String userId) {<br>    return userRepository.findById(userId)          // non-blocking<br>        .flatMap(user -&gt; orderService.getOrders(user.getId()))  // non-blocking<br>        .flatMap(orders -&gt; buildProfile(user, orders))<br>        .map(this::sanitize);<br>}</pre><p>No thread blocks. The event loop handles thousands of concurrent I/O operations with a handful of OS threads. Throughput scales dramatically.</p><p>It worked. But it came at a serious cost.</p><h3>The Real Cost of Reactive Programming</h3><p>Reactive code is genuinely harder to work with. Not because developers are lazy, but because it fundamentally changes how programs are structured.</p><h3>1. Stack traces become useless</h3><p>When something goes wrong in a reactive pipeline, the stack trace looks like this:</p><pre>java.lang.NullPointerException<br>    at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:100)<br>    at reactor.core.publisher.FluxFlatMap$FlatMapMain.tryEmit(FluxFlatMap.java:543)<br>    at reactor.core.publisher.FluxFlatMap$FlatMapInner.onNext(FluxFlatMap.java:984)<br>    at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:157)<br>    ...</pre><p>The actual line in your application code where the null originated is buried, or missing entirely. Debugging reactive code in production is significantly harder than debugging synchronous code.</p><h3>2. The mental model is non-linear</h3><p>Synchronous code reads top to bottom. You can step through it in a debugger. You can reason about it sequentially.</p><p>Reactive code is a composition of asynchronous operators. Understanding what happens when flatMap fires on a Flux that has already been cancelled, or why your zipWith is not emitting, these require a deep understanding of the reactive specification that most developers never fully internalize.</p><h3>3. Mixing reactive and blocking code breaks everything</h3><p>The cardinal sin in reactive programming is calling a blocking method inside a reactive pipeline. It pins the event-loop thread, defeats the entire model, and causes the performance to collapse.</p><pre>// This looks fine: it is not<br>public Mono&lt;User&gt; getUser(String id) {<br>    return Mono.just(id)<br>        .map(userId -&gt; jdbcTemplate.queryForObject(...)); // BLOCKING: never do this<br>}</pre><p>In a large codebase, maintaining the discipline to never accidentally call a blocking API inside a reactive chain requires constant vigilance. It’s a constraint that doesn’t exist in synchronous code.</p><h3>What Virtual Threads Actually Do</h3><p>Virtual Threads don’t change the programming model. They change the cost of the old programming model.</p><p>A Virtual Thread is a thread managed by the JVM, not the OS. It behaves exactly like a regular Java thread, it has a stack, it blocks, it runs code sequentially. But when it blocks on I/O, the JVM <strong>unmounts it from its OS carrier thread</strong>. The carrier thread goes off to run another Virtual Thread. When the I/O completes, the Virtual Thread is remounted and continues exactly where it left off.</p><pre>// Virtual Threads: plain blocking code<br>public UserProfile getProfile(String userId) {<br>    User user = userRepository.findById(userId);          // blocks: VT unmounts<br>    List&lt;Order&gt; orders = orderService.getOrders(user.getId()); // blocks: VT unmounts<br>    return buildProfile(user, orders);<br>}</pre><p>This code blocks. The Virtual Thread pauses at each database call. But the OS thread it was running on is freed immediately, available to run other Virtual Threads.</p><p>The result: you write simple, sequential, debuggable code, and the JVM handles the concurrency.</p><h3>The Direct Comparison</h3><p>The same endpoint, written two ways:</p><pre>// Reactive : WebFlux<br>@GetMapping(&quot;/profile/{userId}&quot;)<br>public Mono&lt;UserProfile&gt; getProfile(@PathVariable String userId) {<br>    return userRepository.findById(userId)<br>        .switchIfEmpty(Mono.error(new UserNotFoundException(userId)))<br>        .flatMap(user -&gt;<br>            Mono.zip(<br>                orderService.getRecentOrders(user.getId()),<br>                preferencesService.getPreferences(user.getId())<br>            ).map(tuple -&gt; buildProfile(user, tuple.getT1(), tuple.getT2()))<br>        )<br>        .map(this::sanitize)<br>        .onErrorResume(UserNotFoundException.class, e -&gt; Mono.error(new ResponseStatusException(NOT_FOUND)));<br>}</pre><pre>// Virtual Threads, Spring MVC<br>@GetMapping(&quot;/profile/{userId}&quot;)<br>public UserProfile getProfile(@PathVariable String userId) {<br>    User user = userRepository.findById(userId)<br>        .orElseThrow(() -&gt; new ResponseStatusException(NOT_FOUND));</pre><pre>    List&lt;Order&gt; orders = orderService.getRecentOrders(user.getId());<br>    Preferences prefs = preferencesService.getPreferences(user.getId());</pre><pre>    return sanitize(buildProfile(user, orders, prefs));<br>}</pre><p>Both handle the same concurrency. Both scale. The Virtual Thread version is readable by any Java developer. The stack trace from the Virtual Thread version is your actual code.</p><h3>The ThreadLocal Problem at Scale</h3><p>When Virtual Threads run in the millions, one issue surfaces: ThreadLocal.</p><p>ThreadLocal stores per-thread data, user context, trace IDs, locale settings. With a traditional thread pool of 200 threads, ThreadLocal values are set, used, and cleaned up reliably within that bounded set.</p><p>With Virtual Threads, there’s no fixed pool. Threads are created freely. ThreadLocal values can accumulate and leak if not cleaned up properly.</p><p>Java 25 introduced the solution: <strong>Scoped Values</strong>.</p><pre>// ThreadLocal, risk of leak at scale<br>static final ThreadLocal&lt;RequestContext&gt; CTX = new ThreadLocal&lt;&gt;();</pre><pre>// Request filter<br>CTX.set(new RequestContext(userId, traceId));<br>chain.doFilter(request, response);<br>CTX.remove(); // easy to forget, especially in exception paths</pre><pre>// Scoped Values, lifecycle is guaranteed<br>static final ScopedValue&lt;RequestContext&gt; CTX = ScopedValue.newInstance();</pre><pre>// Request filter<br>ScopedValue.runWhere(CTX, new RequestContext(userId, traceId), () -&gt; {<br>    chain.doFilter(request, response);<br>});<br>// Value is automatically gone after this block, no cleanup needed, no leaks</pre><p>Scoped Values are immutable within their scope, require no manual cleanup, and are the correct mental model for the Virtual Thread era. If your codebase uses ThreadLocal for request-scoped data, migrating to Scoped Values is the right long-term move.</p><h3>When Reactive Is Still the Right Choice</h3><p>Virtual Threads didn’t make reactive programming wrong. They made it optional for a specific use case, high-concurrency I/O.</p><p>There are still scenarios where reactive is genuinely the better tool:</p><p><strong>1. True streaming with backpressure</strong></p><p>If you’re streaming data to a slow consumer, video processing, large file downloads, real-time analytics, you need backpressure. The producer needs to know when the consumer is overwhelmed and slow down accordingly. Reactive streams have this built in.</p><pre>// Backpressure: producer slows down when consumer is overwhelmed<br>Flux.fromIterable(largeDataSet)<br>    .onBackpressureBuffer(1000) // buffer up to 1000 items, then signal upstream<br>    .flatMap(item -&gt; processSlowly(item), 5) // max 5 concurrent<br>    .subscribe(result -&gt; emit(result));</pre><p>Virtual Threads have no backpressure semantics. You’d have to build this manually.</p><p><strong>2. WebSocket and Server-Sent Events</strong></p><p>Long-lived, bidirectional connections where data flows continuously are a natural fit for reactive. Holding a Virtual Thread open for the lifetime of a WebSocket connection is inefficient, the Virtual Thread would be mostly idle but still allocated.</p><p><strong>3. Existing reactive codebases</strong></p><p>If you have a large, stable, working WebFlux application, don’t rewrite it to use Spring MVC with Virtual Threads just because you can. The risk-to-reward ratio doesn’t make sense. Virtual Threads are a reason not to go reactive in new code, not a reason to abandon reactive in existing code.</p><h3>The Shift in How You Think About Concurrency</h3><p>Before Virtual Threads, scaling a Java service to handle high concurrency required choosing between two worlds:</p><ul><li><strong>Simple code</strong> (blocking, synchronous): easy to write, but didn’t scale</li><li><strong>Scalable code</strong> (reactive, non-blocking): scaled well, but was hard to write and maintain</li></ul><p>Virtual Threads collapse that trade-off.</p><p>Simple, blocking code now scales. You don’t have to choose.</p><p>This is the actual significance of Project Loom, not that it added a new feature to Java, but that it <strong>removed a constraint</strong> that had shaped how Java applications were written for a decade.</p><p>The thread-per-request model isn’t making a comeback because it was always the right idea. It’s back because now it works, at scale, without apology.</p><p><em>Next in the Java series: </em><strong><em>Project Leyden Deep Dive: How the JVM Is Finally Winning the Startup War.</em></strong></p><h3>Beyond the Code: The Realities of Engineering</h3><p>Understanding Virtual Threads changes how you build systems. But making the case for a technology shift at your company, explaining to a team that’s been writing reactive code for three years why the approach is changing, requires communication skills that no technical article teaches.</p><p>I’ve distilled the unwritten rules of navigating these kinds of decisions inside software companies into a practical field guide.</p><p>👉 <a href="https://ankitv2717.gumroad.com/"><strong>Get “Beyond the Offer Letter” on Gumroad here</strong></a>, and learn how software companies actually work so you can accelerate your growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=627943d3e78f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/virtual-threads-the-idea-that-made-reactive-programming-optional-627943d3e78f">Virtual Threads: The Idea That Made Reactive Programming Optional</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>