All posts / Spring Boot

Modern Spring Boot with Java 21 — Virtual Threads, ScopedValue, and Structured Concurrency

NordLearn · · 3 min read

Part of the series “Java 21 & Spring Boot” · part 2 of 5
  1. Immutability in Java 21: Records, Defensive Copying, and Collections
  2. Modern Spring Boot with Java 21 — Virtual Threads, ScopedValue, and Structured Concurrency
  3. Java Virtual Threads Are a Bigger Deal Than You Think
  4. Spring Boot + JPA + Virtual Threads (Java 21): Avoid N+1, OSIV & Pagination Pitfalls
  5. The Complete Guide to RestClient in Spring Boot 3.2 with Java 21 Virtual Threads
On this page

For years, Java developers had to choose between:

  • Simple blocking code that doesn’t scale
    or
  • Reactive / async code that scales but hurts readability

Java 21 finally breaks that trade-off.

With Virtual Threads, ScopedValue, and Structured Concurrency, we can write plain, readable, blocking code that scales to massive concurrency — without @Async, thread pools, or reactive frameworks.

This article shows how to build a modern Spring Boot service that:

  • Runs on Java 21
  • Uses Virtual Threads
  • Propagates a requestId safely
  • Logs the requestId everywhere
  • Executes parallel service calls correctly

Why Virtual Threads matter (the real problem)

Traditional Java servers work like this:

1 request = 1 platform thread

Platform threads:

  • Map directly to OS threads
  • Are expensive (~1–2 MB stack each)
  • Are limited in number
  • Cannot scale when blocked

This means blocking calls (JDBC, REST, filesystem) limit throughput.

That’s why Java developers were pushed toward:

  • Reactive frameworks
  • Callbacks and futures
  • Complex async pipelines

The problem was never blocking — the problem was expensive threads.

Virtual Threads: what actually changed

Virtual Threads (Project Loom) introduce a new execution model:

1 request = 1 virtual thread

Virtual threads:

  • Are extremely cheap (millions are possible)
  • Are scheduled by the JVM, not the OS
  • Mount/unmount automatically during blocking I/O
  • Free the carrier thread while blocked

So when you do this:

Thread.sleep(1000);
jdbcTemplate.query(...);
restTemplate.getForObject(...);

the JVM parks the virtual thread and reuses the OS thread.

Result

✅ Blocking code
✅ Massive concurrency
✅ Simple mental model

Synchronous Java is scalable again.

Spring Boot + Virtual Threads

Spring Boot 3.2+ (and Boot 4) supports virtual threads out of the box.

spring.threads.virtual.enabled=true

That’s it.

Spring MVC controllers now run on virtual threads, not platform threads.

No custom executors.
No reactive rewrite.

Maven configuration (Java 21 + Spring Boot)

Here is a complete **pom.xml** you can copy-paste.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>3.5.10</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.example</groupId>
 <artifactId>virtual-threads-demo</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>virtual-threads-demo</name>
 <description>Virtual Thread Demo project for Spring Boot</description>
 <url/>
 <properties>
  <java.version>21</java.version>
 </properties>
 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>21</source>
                    <target>21</target>
                    <compilerArgs>--enable-preview</compilerArgs>
                </configuration>
            </plugin>
        </plugins>
 </build>

</project>

ThreadLocal

Before Java 21, request context (like requestId) was usually stored using ThreadLocal.

REQUEST_ID.set(id);
try {
    doWork();
} finally {
    REQUEST_ID.remove();
}

This approach is fragile:

  • Forget remove() → memory leaks
  • Thread pools reuse threads
  • Virtual threads break assumptions
  • Context can leak across requests

Java needed a safer abstraction.

ScopedValue (Java 21): context done right

ScopedValue is a replacement for ThreadLocal in request-scoped scenarios.

Key properties:

  • Immutable
  • Lexically scoped
  • Automatically cleaned up
  • Safe with virtual threads
  • Safe with structured concurrency

Think of it as a dynamic method parameter, not thread state.

Defining a request context

public final class RequestContext {

    private RequestContext() {}

    public static final ScopedValue<String> REQUEST_ID =
            ScopedValue.newInstance();
}

Binding requestId at the HTTP boundary

@Component
public class RequestIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws IOException, ServletException {

        String requestId =
                request.getHeader("X-Request-Id");

        if (requestId == null || requestId.isBlank()) {
            requestId = UUID.randomUUID().toString();
        }

        String finalRequestId = requestId;

        ScopedValue.where(RequestContext.REQUEST_ID, finalRequestId)
                .run(() -> {
                    try {
                        response.setHeader(
                                "X-Request-Id",
                                finalRequestId
                        );
                        filterChain.doFilter(request, response);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
    }
}

No set()
No remove()
No cleanup code

When the scope ends, the value is gone.

Why ScopedValue needs no cleanup

A common question:

“Don’t I need to remove it like ThreadLocal?”

No.

ScopedValue.where(REQUEST_ID, id)
           .run(() -> doWork());
// REQUEST_ID is gone here

The JVM enforces the lifetime. Leaks are impossible by design.

Logging requestId without MDC

MDC relies on ThreadLocal, which is exactly what we want to avoid. Instead, logging reads from ScopedValue.

Custom Logback converter

public class RequestIdConverter extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent event) {
        if (RequestContext.REQUEST_ID.isBound()) {
            return RequestContext.REQUEST_ID.get();
        }
        return "-";
    }
}

logback-spring.xml in resources folder

<configuration>

    <!-- Custom converter for ScopedValue requestId -->
    <conversionRule conversionWord="reqId"
                    converterClass="com.example.demo.RequestIdConverter"/>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                %d{yyyy-MM-dd HH:mm:ss} %-5level [%reqId] %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>

</configuration>

Now every log line includes the requestId automatically.

Parallel service calls with Structured Concurrency

Real services often call multiple downstream systems.

Java 21 introduces Structured Concurrency, which treats parallel tasks as one logical unit.

@Service
public class AggregationService {

    private final UserService userService;
    private final OrderService orderService;
    private final RecommendationService recommendationService;

    public AggregationService(
            UserService userService,
            OrderService orderService,
            RecommendationService recommendationService) {
        this.userService = userService;
        this.orderService = orderService;
        this.recommendationService = recommendationService;
    }

    public String aggregate() throws Exception {

        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {

            var user  = scope.fork(userService::getUser);
            var order = scope.fork(orderService::getOrders);
            var rec   = scope.fork(recommendationService::getRecommendations);

            scope.join();
            scope.throwIfFailed();

            return """
                   %s
                   %s
                   %s
                   """.formatted(
                    user.get(),
                    order.get(),
                    rec.get()
            );
        }
    }
}

Why this works so well:

  • Each task runs in a virtual thread
  • Context propagates automatically
  • Failures cancel sibling tasks
  • Lifecycle is explicit and safe

Services

@Service
public class UserService {

    private static final Logger log =
            LoggerFactory.getLogger(UserService.class);

    public String getUser() throws InterruptedException {
        log.info("Fetching user for requestId={}",
                RequestContext.REQUEST_ID.get());
        Thread.sleep(500); // Simulate blocking call
        return "UserData";
    }
}
@Service
public class OrderService {

    private static final Logger log =
            LoggerFactory.getLogger(OrderService.class);

    public String getOrders() throws InterruptedException {
        log.info("Fetching orders for requestId={}",
                RequestContext.REQUEST_ID.get());
        Thread.sleep(700);
        return "OrderData";
    }
}
@Service
public class RecommendationService {

    private static final Logger log =
            LoggerFactory.getLogger(RecommendationService.class);

    public String getRecommendations() throws InterruptedException {
        log.info("Fetching recommendations for requestId={}",
                RequestContext.REQUEST_ID.get());
        Thread.sleep(600);
        return "RecommendationData";
    }
}

RestController Example

@RestController
public class AggregateController {

    private static final Logger log =
            LoggerFactory.getLogger(AggregateController.class);

    private final AggregationService aggregationService;

    public AggregateController(AggregationService aggregationService) {
        this.aggregationService = aggregationService;
    }

    @GetMapping("/aggregate")
    public String aggregate() throws Exception {
        // Log at the controller level
        log.info("Handling /aggregate request, requestId={}",
                RequestContext.REQUEST_ID.get());

        // Run parallel service calls
        String result = aggregationService.aggregate();

        log.info("Completed /aggregate request, requestId={}",
                RequestContext.REQUEST_ID.get());

        return result;
    }
}

How it works

  1. Client sends a request:
GET /aggregate
X-Request-Id: b697731e-5844-4e5a-af6e-fe6de43cf190

2. RequestContextFilter:

  • Reads the header (or generates one)
  • Binds ScopedValue
  • Adds it to the response

3. Controller and all service calls:

  • Access RequestContext.REQUEST_ID.get()
  • Logs automatically include requestId

2026-02-08 18:45:39 INFO  [b697731e-5844-4e5a-af6e-fe6de43cf190] c.e.d.controller.AggregateController - Handling /aggregate request, requestId=b697731e-5844-4e5a-af6e-fe6de43cf190
2026-02-08 18:45:39 INFO  [b697731e-5844-4e5a-af6e-fe6de43cf190] c.e.d.service.RecommendationService - Fetching recommendations for requestId=b697731e-5844-4e5a-af6e-fe6de43cf190
2026-02-08 18:45:39 INFO  [b697731e-5844-4e5a-af6e-fe6de43cf190] c.example.demo.service.OrderService - Fetching orders for requestId=b697731e-5844-4e5a-af6e-fe6de43cf190
2026-02-08 18:45:39 INFO  [b697731e-5844-4e5a-af6e-fe6de43cf190] c.example.demo.service.UserService - Fetching user for requestId=b697731e-5844-4e5a-af6e-fe6de43cf190
2026-02-08 18:45:40 INFO  [b697731e-5844-4e5a-af6e-fe6de43cf190] c.e.d.controller.AggregateController - Completed /aggregate request, requestId=b697731e-5844-4e5a-af6e-fe6de43cf190

4. StructuredTaskScope forks:

  • Parallel tasks inherit the same ScopedValue
  • Logs in parallel services show the same requestId

5. Response headers include the same requestId:

X-Request-Id: b697731e-5844-4e5a-af6e-fe6de43cf190

✅ With Java 21 + Spring Boot:

  • Virtual threads for scale
  • Blocking code for clarity
  • ScopedValue for request context
  • Structured concurrency for parallelism
  • Clean logging without MDC

Happy coding!