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
|
|
If Spring is using virtual threads you will see the following when visiting the end-point http://localhost:8080/hello.
|
|
With the virtual threads disabled the end-point will return the following:
|
|
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.