Video Streaming using Virtual Threads in Spring Boot 3
Sometime back I wrote an article which explains the Virtual Thread capability introduced by Project Loom and showcased how 1 Million Threads can be run in a single JVM.
I wanted to take a step further to check whether it is possible use Virtual Threads for the purpose of Video Streaming. A quick recap, I have written an article on using Spring’s StreamingResponseBody to support video Streaming asynchronously.
I wanted to retrofit this with the more latest Virtual Threads so that the Video Streaming would be able to leverage the features of Virtual Threads when it comes to non blocking, efficient I/O operations which is required for Streaming large files (Movies, Music, etc).
In order to achieve this I had to write a custom AsyncTaskExecutor extending SimpleAsyncTaskExecutor which makes use of Virtual Thread.
@Bean
public AsyncTaskExecutor asyncTaskExecutor() {
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor() {
protected void doExecute(Runnable task) {
Thread.startVirtualThread(task);
}
};
executor.setThreadNamePrefix("async-");
return executor;
}
With this Streaming of the Video will be designated to a Virtual Thread and will be supporting Multiple concurrent streaming of videos per JVM.
The full source code is available in github.