경량(Light Weight) 스레드입니다.OS Thread를 wrapping하여 제공하였으며, 이를 Platform Thread라고 칭합니다.Platform Thread는 OS Thread와 1:1로 대응되며, Platform Thread의 최대 개수는 OS Thread 개수에 의해 제한됩니다.
java.lang.Thread의 인스턴스입니다.Carrier Thread라고 부릅니다.
Blocking I/O 를 만난다면, Java Runtime은 다시 동작이 시작될 수 있을 때까지 Virtual Thread 수행을 연기시킵니다.Mount되어 연산을 수행하던 Carrier Thread는 기존 Virtual Thread와 Unmount되고, 다른 Virtual Thread와 Mount되어 작업을 수행합니다.

ForkJoinPool이 사용되고 있습니다.
Thread.ofVirtual().start()Thread.startVirtualThread()public class VirtualThreadTest {
public static void main(String[] args) {
Runnable runnable = () -> { String test = "test"; };
Thread thread1 = Thread.ofVirtual().start(runnable);
Thread thread2 = Thread.startVirtualThread(() -> { String test = "test"; });
if(thread1.isVirtual()){
System.out.println("thread1 is virtual thread");
}
else {
System.out.println("thread1 is not virtual thread");
}
if(thread2.isVirtual()){
System.out.println("thread2 is virtual thread");
}
else {
System.out.println("thread2 is not virtual thread");
}
}
}
thread1 is virtual thread
thread2 is virtual thread
application.yml, application.properties)파일에 다음과 같이 추가해주면 virtual thread를 사용합니다.spring:
threads:
virtual:
enabled: true
Carrier Thread에 고정됩니다.synchronized block 혹은 method를 실행하는 경우native method를 실행하거나, Foreign Function을 실행하는 경우| 항목 | 내용 | 비고 |
|---|---|---|
| java | JDK 21 | 21는 Virtual Thread가 정식 출시된 최초의 LTS 버전입니다. |
| spring boot | Spring Boot 3.2 | Spring Boot 3.2부터 java 21을 지원합니다. |
| cpu | Apple M1 Pro | Intel Core i9-11900T와 벤치마크가 비슷했습니다. |
| memory | 16GB | |
| 부하테스트 | ngrinder | 가상유저 296명이 1분간 요청 |
@RestController
public class TestController {
@GetMapping("/test")
@ResponseBody
public Map<String, String> test() throws InterruptedException {
Map<String, String> result = new HashMap<>();
Thread.sleep(1000);
return result;
}
}
기존의 Platform Thread를 사용한 경우

Virtual Thread를 사용한 경우

@RestController
public class TestController {
@GetMapping("/test")
@ResponseBody
public Map<String, String> test() {
Map<String, String> result = new HashMap<>();
return result;
}
}
기존의 Platform Thread를 사용한 경우

Virtual Thread를 사용한 경우

| Thread | API | TPS | MMT | Err Rate | Vusers |
|---|---|---|---|---|---|
| Platform Thread | 1초 Blocking | 199.7 | 1478.7 | 0.0% | 296 |
| Virtual Thread | 1초 Blocking | 290.5 | 1024.7 | 5.8% | 296 |
| Platform Thread | 바로 응답 | 14307.3 | 12.3 | 27.3% | 296 |
| Virtual Thread | 바로 응답 | 13584.5 | 12.7 | 30.7% | 296 |
https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html#GUID-DC4306FC-D6C1-4BCC-AECE-48C32C1A8DAA
https://openjdk.org/jeps/444#Thread-local-variables