Upgrading to Java 25 & Spring Boot 4: Concurrency, Virtual Threads, and Latency Tuning
- Published on
- Updated
- Reading time
- 14 mins read
On this page

For over two decades, high-throughput Java backend engineering was shaped by a fundamental constraint: Java platform threads are 1:1 mappings to Operating System (OS) kernel threads.
Because each platform thread consumes roughly 1 MB of stack memory and incurs expensive OS context switching, JVM applications could rarely scale past a few thousand concurrent threads without exhausting memory or choking CPU schedulers. To survive at multi-million RPM scale, the industry pivoted toward asynchronous reactive frameworks like WebFlux, RxJava, and Netty. But reactive programming came at a steep cognitive price: fragmented stack traces, unreadable backpressure pipelines, and debugging sessions that drained developer morale.
Enter Project Loom and Virtual Threads: previewed in Java 19 and 20, final since Java 21, and much easier to adopt on Java 25 LTS alongside Spring Boot 4.0, because a virtual thread that blocks inside synchronized no longer pins its carrier thread (JEP 491, delivered in JDK 24).
I led our coupon domain's upgrade to Java 25 and Spring Boot 4 at Trendyol. The domain sits on the checkout critical path and serves roughly 4M requests per minute at steady state and close to 7M at peak, with most of our latency budget spent in I/O operations (HTTP REST calls, Couchbase document lookups, PostgreSQL queries, and Kafka event publishing).
The promise sounded almost too good to be true: flip spring.threads.virtual.enabled=true, ditch reactive callback hell, write simple blocking imperative code, and achieve massive concurrent throughput.
Here is the unvarnished engineering reality of what happened when we deployed virtual threads to production: what Java 25 changed about carrier thread pinning, why our database connection pools almost melted, how Generational ZGC stabilized latency, and how we moved our services toward SonarQube Grade A.
1. Virtual Threads Architecture: M:N Scheduling
To understand why things broke before they got better, we must understand how Java 25 executes virtual threads under the hood.
Unlike a platform thread, a virtual thread (java.lang.VirtualThread) is a lightweight user-space construct managed by the JVM rather than the OS kernel.
[Virtual Threads (User Space)]
VT-1 VT-2 VT-3 ... VT-50,000
│ │ │ │
▼ ▼ ▼ ▼
┌──────────────────────────────────────────────┐
│ ForkJoinPool Carrier Worker Threads (Kernel) │
│ [Carrier 1] [Carrier 2] ... [Carrier 16]│ (Matches CPU Core Count)
└──────┬─────────────┬────────────────────┬────┘
│ │ │
▼ ▼ ▼
[ OS Core 0 ] [ OS Core 1 ] [ OS Core 15 ]
- When a virtual thread executes on-CPU computation, the JVM mounts it onto a carrier thread (a standard platform thread from an internal
ForkJoinPool). - When the virtual thread encounters a non-CPU blocking operation (such as waiting on an HTTP response, reading a Couchbase document via socket I/O, or sleeping), the JVM unmounts the virtual thread from its carrier thread and parks its call stack on the heap.
- The carrier thread is immediately free to run other runnable virtual threads.
- When the socket I/O completes, the OS epoll/kqueue notifies the JVM, which remounts the virtual thread on any available carrier thread and resumes execution.
Only as many virtual threads as there are carriers are mounted at any instant; the rest wait, parked on the heap. That is why a pod can hold far more concurrent virtual threads than it has CPU cores, and why a waiting virtual thread costs a small heap object instead of a dedicated OS thread stack.
2. The Silent Killer: Carrier Thread Pinning
Pinning is the main reason many teams held back on virtual threads in Java 21. Java 25 removes its most common cause, but not all of them, so it is worth knowing exactly what changed.
What Causes Pinning?
On Java 21, a virtual thread is pinned to its carrier thread when it executes a blocking operation while:
- Inside a
synchronizedblock or method. - Executing a native method (JNI) or Foreign Function & Memory (FFM) call.
When a virtual thread is pinned, it cannot be unmounted. If it blocks on network I/O while pinned, its underlying carrier thread remains hostage.
In a cluster where the carrier pool only has 16 carrier threads:
Carrier 1: [ Pinned in synchronized block waiting for Couchbase socket ]
Carrier 2: [ Pinned in synchronized block waiting for HTTP REST call ]
...
Carrier 16: [ Pinned in synchronized block waiting for PostgreSQL lock ]
-------------------------------------------------------------------------
RESULT (Java 21): Carrier pool 100% starved! Every other virtual thread FROZEN!
Even with the CPU almost idle, no other virtual thread can be scheduled.
JDK 24 removed the first cause (JEP 491), and Java 25 inherits the fix. A virtual thread that blocks inside synchronized, or in Object.wait(), now unmounts and releases its carrier. What still pins on Java 25 is a much narrower set: native code (a JNI method or an FFM call) that calls back into Java code which then blocks, blocking while a class is being loaded or inside a class initializer, and waiting for another thread to finish initializing a class.
Hunting Down Pinning with JVM Tracing & JFR
Older guides tell you to run with -Djdk.tracePinnedThreads=full. That system property was removed in JDK 24 together with JEP 491, and on Java 25 setting it does nothing:
# No effect on Java 25 (removed in JDK 24)
-Djdk.tracePinnedThreads=full
The tool that still works is Java Flight Recorder (JFR). Its jdk.VirtualThreadPinned event is enabled by default with a 20 ms threshold, and since JDK 24 it also records why the thread was pinned. We lowered the threshold in the JFR settings of our staging deployments:
<event name="jdk.VirtualThreadPinned">
<setting name="enabled">true</setting>
<setting name="stackTrace">true</setting>
<setting name="threshold">10ms</setting>
</event>
Pinning was only half of the audit. A monitor held across I/O no longer pins on Java 25, but it still makes every caller queue behind it, so we went looking for those too:
Culprit: Legacy In-Memory Cache Mutexes
A shared internal token cache used a synchronized method around an HTTP token-refresh call:
// Anti-Pattern: Monitor Held Across Network I/O
public class LegacyOAuthTokenManager {
private String cachedToken;
private Instant expiryTime = Instant.MIN;
public synchronized String getValidToken() {
if (Instant.now().isAfter(expiryTime)) {
// BLOCKING HTTP CALL INSIDE SYNCHRONIZED METHOD!
// Java 21: pins the carrier thread for the entire network duration (~45ms)
// Java 25: no pinning, but every caller still queues on this monitor
this.cachedToken = authClient.requestNewTokenBlocking();
this.expiryTime = Instant.now().plusSeconds(300);
}
return this.cachedToken;
}
}
The Fix: Refactoring to ReentrantLock and StampedLock
java.util.concurrent.locks.ReentrantLock never pinned, even on Java 21, and on Java 25 synchronized doesn't either, so the lock type is no longer the point. The point is the fast path: a lock-free volatile read serves every caller while the token is valid, and only a refresh takes the lock. A virtual thread that does wait for the ReentrantLock unmounts cleanly from the carrier thread:
// Fixed: Virtual-Thread Friendly with ReentrantLock
public class ResilientOAuthTokenManager {
private final ReentrantLock lock = new ReentrantLock();
private volatile String cachedToken;
private volatile Instant expiryTime = Instant.MIN;
public String getValidToken() {
// Fast path: lock-free volatile read
if (Instant.now().isBefore(expiryTime) && cachedToken != null) {
return cachedToken;
}
lock.lock();
try {
// Double-checked locking
if (Instant.now().isBefore(expiryTime) && cachedToken != null) {
return cachedToken;
}
// Blocking I/O unmounts virtual thread cleanly
this.cachedToken = authClient.requestNewTokenBlocking();
this.expiryTime = Instant.now().plusSeconds(300);
return cachedToken;
} finally {
lock.unlock();
}
}
}
We audited our services for synchronized methods enclosing I/O calls and restructured them the same way, with ReentrantLock, StampedLock, or non-blocking primitives where a lock was still needed.
3. Database Connection Pool Sizing: HikariCP with Virtual Threads
The second major operational landmine when adopting virtual threads is database connection pools.
In the old platform-thread world, your thread pool was naturally bound by server.tomcat.threads.max=200. Since you could only have 200 concurrent requests executing, a HikariCP pool of maximum-pool-size: 50 was reasonably well-balanced.
With virtual threads enabled, that cap is gone (server.tomcat.threads.max no longer has any effect), and your application can effortlessly accept and begin processing thousands of concurrent requests, up to Tomcat's max-connections limit.
If each of those virtual threads immediately invokes couponRepository.findById(id):
- Thousands of virtual threads concurrently attempt to borrow a connection from HikariCP.
- HikariCP's queue of waiting borrowers grows far faster than connections are returned.
- Connection acquisition timeouts (
Connection is not available, request timed out after 30000ms) explode.
The Naive Trap: Don't Increase the Pool to 1,000
Junior and intermediate engineers often suggest: "If we have 10,000 threads, let's just scale HikariCP maximumPoolSize from 50 to 1,000!"
Do not do this.
A PostgreSQL or Oracle instance cannot handle 1,000 active concurrent queries without massive context switching, disk seek contention, and buffer pool eviction. PostgreSQL spawns a dedicated backend process for every single connection. Having 1,000 concurrent processes executing queries will quickly cause CPU load on the database server to spike past 100, collapsing your database.
The Solution: Little's Law & Concurrency Limiting via Semaphores
We kept our HikariCP pool lean and placed a virtual-thread-aware bulkhead semaphore in front of database operations:
# application.yml
spring:
threads:
virtual:
enabled: true
datasource:
hikari:
maximum-pool-size: 40
minimum-idle: 40
connection-timeout: 5000
idle-timeout: 600000
max-lifetime: 1800000
@Component
public class DatabaseAccessBulkhead {
// Bound DB access to match physical connection pool capacity
private final Semaphore dbSemaphore = new Semaphore(40, true);
public <T> T executeWithPermit(Supplier<T> dbOperation) {
try {
if (!dbSemaphore.tryAcquire(2, TimeUnit.SECONDS)) {
throw new DatabaseSheddingException("Database pool congested. Request shed.");
}
try {
return dbOperation.get();
} finally {
dbSemaphore.release();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Operation interrupted");
}
}
}
By bounding concurrent database borrowers to 40 permits, virtual threads queue in memory without creating connection pool stampedes or exhausting database CPU.
4. Replacing ThreadLocal with Java 25 Scoped Values
For decades, ThreadLocal was the default mechanism to propagate contextual data (such as security principals, tracing IDs, and transaction contexts) down the call stack.
In a platform thread pool, you allocate a fixed number of ThreadLocal maps. But when you spawn 100,000 virtual threads, each holding multiple ThreadLocal variables:
- Memory Bloat: 100,000 copies of request metadata accumulate on the heap.
- Mutability & Leak Risks: If a
ThreadLocalis not cleaned up viaremove()in afinallyblock, references linger for the life of the thread, and on pooled threads they leak into subsequent workloads.
In Java 25, where they are final (JEP 506), we replaced ThreadLocal with Scoped Values (java.lang.ScopedValue).
Scoped Values are immutable, bound only for the dynamic scope of a single call, and designed with virtual threads in mind:
public class SecurityContextHolder {
public static final ScopedValue<UserContext> CURRENT_USER = ScopedValue.newInstance();
public static <T> T runAs(UserContext user, Callable<T> task) throws Exception {
// Bound exclusively for the duration of the callable
return ScopedValue.where(CURRENT_USER, user).call(task::call);
}
}
// In service layer:
public CouponEvaluationResult evaluateCoupon(String couponCode) {
// Cheap lookup; the binding disappears automatically when the scope exits
UserContext user = SecurityContextHolder.CURRENT_USER.get();
return couponEngine.apply(couponCode, user.getCustomerId());
}
Because a binding cannot outlive the call that established it, the forgotten-remove() leak disappears entirely. (If you used the earlier previews: ScopedValue.callWhere and runWhere were removed in JDK 24, so where(...).call(...) and where(...).run(...) are the way in.)
5. Garbage Collection in Java 25: Generational ZGC
Virtual thread workloads produce a distinct memory allocation profile: millions of short-lived virtual thread objects, frame stacks, and continuation buffers allocated and discarded in milliseconds.
Under G1, which is still the default collector in Java 25, our young collection frequency jumped significantly during load bursts, causing latency jitter.
We switched to Generational ZGC. Since JDK 24, ZGC is generational-only (JEP 490), so -XX:+UseZGC is all it takes. Generational ZGC separates objects into young and old generations while doing its expensive work concurrently with application threads, and its pauses are measured in microseconds (JEP 439).
# Production JVM Flags for Java 25 Checkout Services
# (no -XX:+ZGenerational: obsolete since JDK 24, ZGC is always generational)
-XX:+UseZGC
-XX:MaxRAMPercentage=75.0
-XX:+AlwaysPreTouch
-XX:+UseNUMA
The Latency Stability Transformation
The difference showed up in the tail rather than the median: the latency spikes that lined up with G1 pauses during allocation bursts went away, because ZGC's pauses are measured in microseconds rather than milliseconds.
6. Code Quality & SonarQube Grade A Compliance
Upgrading production services across a major framework version requires rigorous quality gates, and it is also the moment to retire older conventions:
- Spring Boot 4 moves the baseline to Jakarta EE 11 (the
javax.*tojakarta.*namespace migration already happened in Spring Boot 3). - Modern record patterns and pattern matching for
switchreplace verbose instanceof casts. - Structured concurrency (
StructuredTaskScope) is the direction for coordinating parallel subtasks instead of raw uncoordinatedCompletableFuturechains, but in Java 25 it is still a preview API (JEP 505) that needs--enable-preview.
We moved 16 services toward SonarQube Grade A, gating on our internal Quality Gate rules:
- 0 Blocker or Critical Bugs.
- 0 Security Hotspots.
- Unit and Integration Test Coverage on new code (validated with Testcontainers and WireMock).
- A-Grade Maintainability, Reliability, and Security ratings as the target.
// Example: Switch Expressions & Structured Concurrency (preview API in Java 25, needs --enable-preview)
public CouponValidationResult validateBasket(Basket basket) {
try (var scope = StructuredTaskScope.open()) {
Supplier<UserQuota> quotaSubtask = scope.fork(() -> quotaClient.fetchQuota(basket.userId()));
Supplier<List<Rule>> rulesSubtask = scope.fork(() -> ruleEngine.fetchApplicableRules(basket.items()));
scope.join(); // Join subtasks in parallel; throws FailedException if either fails
UserQuota quota = quotaSubtask.get();
List<Rule> rules = rulesSubtask.get();
return switch (quota.status()) {
case ACTIVE -> quota.remainingLimit() > 0
? new CouponValidationResult.Approved(rules)
: new CouponValidationResult.Rejected("Campaign quota depleted");
case EXHAUSTED -> new CouponValidationResult.Rejected("Campaign quota depleted");
case SUSPENDED -> new CouponValidationResult.Suspended("Account verification required");
};
} catch (StructuredTaskScope.FailedException | InterruptedException e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
log.error("Failed parallel basket validation", e);
return new CouponValidationResult.Error("Service temporarily degraded");
}
}
Summary: Platform Threads vs Java 25 Virtual Threads
Here is what the upgrade changed across our services, in one place:
Concern │ Before (Platform Threads) │ Java 25 + Spring Boot 4
───────────────────────────────┼─────────────────────────────┼────────────────────────────────────────
Request Concurrency Ceiling │ Tomcat worker pool │ Explicit DB bulkhead + connection pool
Blocking Inside synchronized │ Holds a platform thread │ Unmounts, no pinning (JEP 491)
Pinning Diagnostics │ n/a │ JFR jdk.VirtualThreadPinned
Request Context Propagation │ ThreadLocal │ ScopedValue (final, JEP 506)
Garbage Collector │ G1 │ Generational ZGC
Parallel Subtasks │ CompletableFuture chains │ StructuredTaskScope (preview, JEP 505)
The Staff Engineer Checklist for Virtual Threads
If your team is planning to adopt Java 25 and Spring Boot 4 for mission-critical services, follow these engineering guidelines:
- Verify Your Dependencies with JFR, Not Old Flags: On Java 25,
synchronizedno longer pins and-Djdk.tracePinnedThreadsis gone. Recordjdk.VirtualThreadPinnedin staging under stress; what is left to find is native code that calls back into blocking Java code, and blocking during class loading or initialization. - Never Scale HikariCP Linearly with Virtual Threads: Virtual threads decouple concurrent requests from OS threads, but your database is still bounded by CPU and disk IOPS. Guard connection pools with Semaphores.
- Adopt Scoped Values Over
ThreadLocal: Eliminate memory leaks and cut heap allocation overhead by binding request context to a bounded dynamic scope. - Pair Virtual Threads with Generational ZGC: The massive volume of short-lived virtual thread objects demands a concurrent collector whose stop-the-world pauses stay in the microseconds.
- Embrace Structured Concurrency: Replace fragile
CompletableFuturechains withStructuredTaskScopeto maintain clear parent-child thread lifecycles and clean cancellation semantics, keeping in mind that it is still a preview API in Java 25 and has changed between releases.