Contents

Use Virtual Threads with Spring

Writen by: David Vlijmincx

Introduction

In this post, I quickly wanted to show you how to use virtual thread with Spring. All you have to do is enable it. That is if you are already running Java 21 and using Spring 3.2.0 or later.

Enabling Virtual Threads

To enable virtual threads all you need to do is to create an applications.properties file in the resource directory if you don't have one already, and add the following line:

spring.threads.virtual.enabled=true

When you add the previous line all requests will be handled by Virtual threads.

Verifying the result

Let's see if setting the property works by getting the thread name. To do this I will use the RestController

1
2
3
4
5
6
7
8
9
@RestController
public class SampleClass {

    @GetMapping("hello")
    String helloWorld(){
        return "Hello World from " + Thread.currentThread();

    }
}

If Spring is using virtual threads you will see the following when visiting the end-point http://localhost:8080/hello.

1
Hello World from VirtualThread[#83,tomcat-handler-1]/runnable@ForkJoinPool-1-worker-1

With the virtual threads disabled the end-point will return the following:

1
Hello World from Thread[#75,http-nio-8080-exec-5,5,main]

Conclusion

Enabling Virtual threads in Spring is very straight forward. All you need is to add a line to the application properties file. The hard part is verifying if using Virtual threads does indeed give you better performance.